c - 如何将一个或多个变量传递给新创建的线程?

标签 c linux pthreads

我现在正在学习线程。我想知道是否可以将变量传递给我的线程。我的任务是创建一个线程并为每个线程分配一个数字(如果愿意的话可以命名)并每 100 毫秒打印该数字。我当前的程序如下:

#define PCHECK(sts,msg) if((sts)!=0){printf("error : %s\n",msg); exit(EXIT_FAILURE)}
#define NB_THREAD 5

void* do_nothing(void* data)
{
    int i;

    //printf("creation thread %d",(int)data);
    while(1)
    {
        usleep(100000);
    printf("thread number : %d \n",data);
    }
    i = 0;
    pthread_exit(NULL);   
    //exit(EXIT_SUCCESS);
}

int main(int argc, char *argv[])
{
    int pid, j, status;
    pthread_t thread;
    int * res;
    int stat;

    for (j = 0; j < NB_THREAD; j++)
    {
        stat = pthread_create(&thread, NULL, do_nothing, (void *) j );
        if (stat !=0)
        {
            perror ("pthread_create()");
        }
    }
    for (j = 0; j < NB_THREAD; j++)
    {
        pthread_join(thread, (void **) &res );
    }



    return EXIT_SUCCESS;
}

目前唯一打印的数字是 0(数据值)。有人可以指出我哪里出错了,谢谢:)

最佳答案

这里有一些关于如何将参数传递给 pthread 的好例子

[1] https://computing.llnl.gov/tutorials/pthreads/#PassingArguments

关于c - 如何将一个或多个变量传递给新创建的线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10663205/

相关文章:

c - 将字符数组解析为指针数组中的单词(C 编程)

c - 如何读取c中的换行符

python - 将 python C 包安装到 bin 文件夹中

linux - CentOS 6 VNC 服务器拒绝连接

c - rpm 减小共享库的大小

c - pthreads 中的段错误,Linux Ubuntu

c - 这段代码中哪些变量部分存储到堆栈中?

c - 将多个文件内容写入单个文件的有效方法

c - 调用 pthread_spin_destroy() 时,到底释放了什么 "resources"?

linux - Node.js 未捕获异常