如何在 C 中将字符串作为参数传递给线程

How to pass a string as an argument for a thread in C

我是 C 和编程的新手,我正在尝试将字符串传递到线程中,以便稍后对其进行操作。我已经尝试使用数组 char string[] = "word" 创建字符串并将其传递给线程 - 现在是一个指针 char *word = "word" 没有运气。如何将字符串作为参数传递给线程?

#include <stdio.h>
#include <stdlib.h> // exit calls
#include <pthread.h> // contains thread package

void *print_string_in_reverse_order(void *str)
{
    char *string = (char *)str;
    printf("%s\n", *string); // this won't print anything

    pthread_exit(NULL); // exit the thread
}

int main(int argc, char *argv[])
{
    pthread_t threadID;
    char *word = "word"; //should this be an array?
    printf("In function main(): Creating a new thread\n");

    // create a new thread in the calling process
    int status = pthread_create(&threadID, NULL, print_string_in_reverse_order, (void *)&word);

}

你的问题是,当你使用 &word 时,你正在将指针传递给指向字符串的指针,你需要在 pthread_create 参数中只使用 word

这是因为你声明的时候

const char* word = "my word";

"my world" 的内存分配在只读全局内存中,然后 word 成为指向堆栈上该内存的指针。请注意,即使未将 word 声明为 const,您也无法修改字符串。

const char word[] = "my word";

为 "my word" 创建一个大数组。这通常不安全地传递给另一个线程,因为内存被删除然后堆栈在函数结束时展开。

声明可修改字符串的最简单安全方法是声明如下内容:

static char word[] = "my word";

这样可以保证"my word"在全局内存中,肯定可用,否则就需要使用malloc

分配内存
  1. pthread_create(...., (void *)&word);

您将地址传递给指针。 &word 的类型为 char** - 它是指向 char 的指针。因此,您可以将其作为 char** 获取,然后取消引用指针(并确保地址 &word 对其他线程执行有效),或者只传递 word 而不是您可能是故意的。

  1. printf("%s\n", *string); - *stringchar,而不是 char*%s 扩展指向类型为 char* 的零终止字符数组的指针。启用编译器警告并听取它们 - 编译器应该警告此类错误。

  2. 退出程序前必须先加入线程。因为 mainpthread_create 之后就退出了,你的程序退出了,另一个线程也退出了。因为第二个线程没有足够的 cpu 时间来执行 printf 语句,所以什么也没有打印出来(如果其余代码有效..

所以你可能想要:

void *print_string_in_reverse_order(void *str) {
    char *string = str;
    printf("%s\n", string);
    return NULL;
}

int main(int argc, char *argv[]) {
    pthread_t threadID;
    const char *word = "word"; // string literals are immutable
    printf("In function main(): Creating a new thread\n");
    int status = pthread_create(&threadID, NULL, print_string_in_reverse_order, word);
    pthread_join(threadID, NULL);
}