c - pthreads 线程间共享内存

标签 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
}

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

我想知道的是:如果我将变量 i 作为 pthread 启动例程的参数传递并且 i 的值发生变化(因为 i 在下一个循环迭代时递增),已经存在的线程中的 i 的值是否也发生变化?

最佳答案

如果您将 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]);

在函数中:

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

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

您可能也有兴趣了解 OpenMP它旨在使您的要求完全自动化。

关于c - pthreads 线程间共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22403799/

相关文章:

android - 文件描述符 3 的 bash 重定向是读取 tcp 端口和写入文本文件的最有效方法吗?

java - 更改方法的参数

java - 如果Java中创建的对象存储在堆中,我们如何能够创建多个同名对象

linux - 如何在 debian 64 位上正确安装 wkhtmltopdf?

c - 按排序顺序生成随机数

c - 我如何才能比其他人更快地获得此 C 代码?

c - 获取任意数据的函数 : Use void* or char*?

c++ - 在 Linux 中正确部署 Qt 应用程序

java - 使用线程同时散列(sha1)多个文件

c - 使用 `scanf()` 读取逗号分隔的输入