pthreads在线程之间共享内存

use*_*085 0 c linux multithreading pthreads

因此,我有一小段代码在理论上可以轻松进行解析。

结构非常简单,非常类似于以下内容:

for (int i = 0; i < some_value; ++i) {
    // we have a function called do_stuff
    // somewhere in the code

    // Create a new pthread
    // using do_stuff as start routine
}
Run Code Online (Sandbox Code Playgroud)

现在,所有变量都不在线程之间共享。即,不需要线程之间的变量间通信。但是我确实使用变量i将数据写入数组等。

我想知道的是:如果我将变量i作为pthread启动例程的参数传递,并且i更改的值(因为i在下一个循环迭代中增加),那么i现有线程中的值是否也会更改?

Sha*_*baz 5

如果将的地址传递i给所有函数,并且每个函数都试图对其进行修改,那么当然i会搞砸了,因为它们都具有相同变量的地址。您需要为每个线程提供需要处理的范围,并让它们使用局部变量对其进行迭代。像这样:

struct thread_data
{
    int start;
    int end;
    pthread_t tid;
};

struct thread_data td[N]; // assuming N threads

/* divide up the ranges */
for (i = 0; i < N; ++i)
    td[i] = (struct thread_data){ .start = i*len/N, .end = (i+1)*len/N };
td[N-1].end = len;

/* create the threads */
for (i = 0; i < N; ++i)
    pthread_create(&td[i].tid, NULL, func, &td[i]);
Run Code Online (Sandbox Code Playgroud)

并在功能上:

void *func(void *arg)
{
    struct thread_data *data = arg;

    for (int i = data->start; i < data->end; ++i)
        /* do some work */
}
Run Code Online (Sandbox Code Playgroud)

您可能还会对OpenMP感兴趣,该OpenMP旨在完全自动化您的要求。