繁体   English   中英

如何将字符串作为参数传递给 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";

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

const char word[] = "my word";

为“我的话”创建一个大数组。 这通常传递给另一个线程是不安全的,因为内存被删除然后堆栈在函数结束时展开。

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

static char 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM