确保每个线程

时间:2015-04-30 22:11:58

标签: c multithreading pthreads posix pthread-join

我想运行4个不同的线程调用相同的方法,我想确保每个运行都来自不同的运行线程。

使用下面提供的代码,方法函数运行预期的次数,但它总是由同一个线程完成(打印值不会改变)。

我应该在代码中更改什么来确保这种情况? (这将导致此示例打印出4个不同的值)

编辑:相同的代码,但包括一个结构,以了解解决方案将如何

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <errno.h>

struct object{
  int id;
};

void * function(void * data){

    printf("Im thread number %i\n",     data->id);
    pthread_exit(NULL);

}

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

    int i;
    int error;
    int status;
    int number_threads = 4;

    pthread_t thread[number_threads];

    struct object info;

    for (i = 0; i < number_threads; ++i){

        info.id = i;

        error = pthread_create(&thread[i], NULL, function, &info);

        if(error){return (-1);}
    }

    for(i = 0; i < number_threads; i++) {

        error = pthread_join(thread[i], (void **)&status);

        if(error){return (-1);}   
    }

}

2 个答案:

答案 0 :(得分:1)

尝试修改

printf("Im thread number %i\n", data);

printf("Im thread number %i\n", *((int *)data));

答案 1 :(得分:1)

您正在将i的地址传递给所有不属于您想要的4个主题,并且会导致 race condition 。如果您只想传递i的值并通过所有线程打印它们,则传递为:

error = pthread_create(&thread[i], NULL, function, (void *)i);

并将打印行更改为:

printf("Im thread number %i\n", (int)data);
相关问题