c - pthread_create int 而不是 void

标签 c pthreads

我有以下代码:

for(i = 0 ; i < max_thread; i++)
{
    struct arg_struct args;
    args.arg1 = file;
    args.arg2 = word;
    args.arg3 = repl;
    if(pthread_create(&thread_id[i],NULL,&do_process,&args) != 0)
    {
        i--;
        fprintf(stderr,RED "\nError in creating thread\n" NONE);
    }
}
for(i = 0 ; i < max_thread; i++)
    if(pthread_join(thread_id[i],NULL) != 0)
    {
        fprintf(stderr,RED "\nError in joining thread\n" NONE);
    }


int do_process(void *arguments)
{
//code missing
}

*如何将 (void *)do_process 转换为 (int) do_process ?*

该函数返回非常重要的信息,没有这些返回我不知道如何阅读回复

我收到以下错误:警告:传递 `pthread_create' 的 arg 3 使指针来自没有转换的整数

最佳答案

线程函数返回一个指针。至少,您可以动态分配一个整数并返回它。

void * do_process (void *arg) {
    /* ... */
    int *result = malloc(sizeof(int));
    *result = the_result_code;
    return result;
}

然后,您可以从 thread_join() 调用中恢复此指针;

    void *join_result;
    if(pthread_join(thread_id[i],&join_result) != 0)
    {
        fprintf(stderr,RED "\nError in joining thread\n" NONE);
    } else {
        int result = *(int *)join_result;
        free(join_result);
        /* ... */
    }

关于c - pthread_create int 而不是 void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18411062/

相关文章:

返回 malloc 的函数内出现 C 错误?

objective-c - 在后台生成图像

使用 pthread.c 创建线程

c++ - 如果我在未使用的 pthread_t 上调用 pthread_join() 会发生什么?

c - 打印返回结构的成员

c - 强制线程之间进行通信

c++ - 线程 vector 中的假缓存共享 C++

c - 将 for 循环索引传递给 C 中的 pthread_create 参数对象

c++ - 父进程没有捕获他所有的子进程

c - WNOHANG 是否清理子资源