保证每个线程的执行

Assure the execution of every thread

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

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

我应该在代码中更改什么以确保这种情况? (这将导致此示例打印 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);}   
    }

}

尝试修改

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

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

您将 i 的地址传递给所有 4 个线程,这不是您想要的,它会导致 race condition。如果您只是想传递 i 的值并让所有线程打印它们,则传递为:

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

并将打印行更改为:

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

您总是看到相同值的原因

您正在将指针打印为整数。 data 指向您 main 中的变量 ii 的地址不会改变,因此打印相同的值。

正在打印 i

的值

您要做的是将 data 取消引用为整数。正确的方法很简单:*(int *)data。这意味着将 data 指针转换为整数,然后取消引用以检索值。


What should I change in the code to assure this condition? (which will result in this example in having 4 different values printed)

打印 i 的值不会 保证打印 4 个不同的值。

  • 完全有可能调度程序不会 运行 您的线程,直到创建所有 4 个线程并且主要线程正在等待 join()。在这种情况下,所有线程都会打印 0.

  • 有可能线程1和2读到i = 2,线程3和4读到i = 3。或者其他一些组合。

如何确保打印出不同的值

要正确执行此操作,您需要向每个线程传递不同的参数。 最干净的应该是这样的。

int thread_number[4] = {0, 1, 2, 3};
// ...
error = pthread_create(&thread[i], NULL, function, &thread_number[i]);