C:如何安全正确地将多个参数传递给 pthread?

标签 c multithreading pthreads

<分区>

考虑这个简单的代码:

void* threadFunction(void* arg) {

    int argument=(int)arg;

    printf("%d recieved\n", argument);

    return NULL;
}


int main(int argv, char* argc[]) {

    int error;
    int i=0;
    pthread_t thread;

    int argument_to_thread=0;

    if ((error=pthread_create(&thread, NULL, threadFunction, (void*)argument_to_thread))!=0) {
        printf("Can't create thread: [%s]\n", strerror(error));
        return 1;
    }

    pthread_join(thread, NULL);


    return 0;
}

这行得通,但有两件事困扰着我。
首先,我想向 threadFunction() 发送多个参数。
当然,我可以传递一个指向数组的指针,但是如果我想传递两个不同类型的参数呢? (比如 intchar*)如何实现?

这里困扰我的第二件事是编译上述内容时收到的警告...

test2.c: In function ‘threadFunction’:
test2.c:8:15: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
  int argument=(int)arg;
               ^
test2.c: In function ‘main’:
test2.c:24:59: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
  if ((error=pthread_create(&thread, NULL, threadFunction, (void*)argument_to_thread))!=0) {
                                                           ^

现在,我可以通过这样做来解决这个问题:

if ((error=pthread_create(&thread, NULL, threadFunction, (void*)&argument_to_thread))!=0) {
    printf("Can't create thread: [%s]\n", strerror(error));
    return 1;
}

但是假设我不想通过引用传递它...有没有办法在编译器不警告我的情况下通过值作为参数传递,比如说...一个 int?

最佳答案

有两种方法:

  1. 使用malloc 获取参数结构的存储空间,并让新线程在处理完参数后负责调用free。 (注意:如果 pthread_create 失败,您需要在失败路径中释放此存储。)

  2. 使用信号量(或其他同步,但信号量是迄今为止最轻的)。

这是后者的一个例子:

struct args {
    int a;
    char *b;
    sem_t sem;
};

void *thread_func(void *p)
{
    struct args *args = p;
    int a = args->a;
    char *b = args->b;
    sem_post(args->sem);
    ...
}

    /* in caller */
    struct args args;
    args.a = ...;
    args.b = ...;
    sem_init(&args.sem, 0, 0);
    pthread_create(&tid, 0, thread_func, &args);
    sem_wait(&args.sem);
    ...

关于C:如何安全正确地将多个参数传递给 pthread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090226/

相关文章:

c - 在 C 函数中声明全局变量(数组)

c - 结构操作需要一些解释

linux - 多线程游戏程序突然锁定在glXSwapBuffers上

java - 为什么当有一个尚未完成的完成阶段时主线程不终止?

python - 调用函数时结束该线程的最佳方法是什么?

c - 跟踪 Pthread 完成的顺序

c - malloc 失败并返回 NULL

c - ds_list 不能处理超过 3 个元素

c++ - 在多线程程序中退出程序

c - 从 pthread 到 main 的信号