【问题标题】:posix pthread work on array elements in separate threadsposix pthread 在单独的线程中处理数组元素
【发布时间】:2017-02-13 21:19:05
【问题描述】:

我正在尝试学习 posix,并希望从一些简单的事情开始。我想在不同线程上处理数组元素。我的代码是:

#include <iostream>
#include <pthread.h>
using namespace std;

static void* doWork(int* a, size_t s) {
    for(int i = 0; i < s; i++) {
        a[i] = a[i] * 2;
    }
    //return void;
}

void printIntArr(int* a, size_t s) {
    for(int i = 0; i < s; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}

int main() {

    int a[24];
    for(int i = 0; i < 24; i++) {
        a[i] = i;
    }

    printIntArr(&a[0], 24); //before

    //I want to make 2 threads, and pass first half and second half of the array to process
    pthread_t tA, tB;
    int resultA =  pthread_create(&tA, NULL, &doWork(&a[0],12), NULL);
    int resultB =  pthread_create(&tB, NULL, &doWork(&a[11],12), NULL);

    printIntArr(&a[0], 24); //after

    return 0;
}

我只想在不同线程的数组的前半部分和后半部分执行doWork 函数。是的,我的代码无法编译。

【问题讨论】:

  • 可能想pthread_join 启动这些线程,然后再枚举和打印它们正在修改的内容。获得一本关于 pthreads 的好书。这很值得。如果您使用的是相当新的 C++(11 或更高版本),请改用 &lt;thread&gt;。这确实是现代 C++ 线程世界的晚餐。

标签: c++ pthreads posix


【解决方案1】:
#include <iostream>
#include <pthread.h>
using namespace std;

typedef struct {
    int* a;
    size_t s;
} Params;

static void* doWork(void * data) {
    Params * p = (Params *) data;
    for(int i = 0; i < p -> s; i++) {
        p ->a[i] = p ->a[i] * 2;
    }
    //return void;
    return data;
}

void printIntArr(int* a, size_t s) {
    for(int i = 0; i < s; i++) {
        cout << a[i] << " ";
    }
    cout << endl;
}

int main() {

    int a[24];
    for(int i = 0; i < 24; i++) {
        a[i] = i;
    }

    printIntArr(&a[0], 24); //before

    Params p1;
    p1.a = &(a[0]);
    p1.s = 12;

    Params p2;
    p2.a = &(a[11]);
    p2.s = 12;


    //I want to make 2 threads, and pass first half and second half of the array to process
    pthread_t tA, tB;
    int resultA =  pthread_create(&tA, NULL, doWork, (void *)&p1);
    int resultB =  pthread_create(&tB, NULL, doWork, (void *)&p2);

    pthread_join(tA, NULL);
    pthread_join(tA, NULL);

    printIntArr(&a[0], 24); //after

    return 0;
}

如果你用 C++ 编码,你可以使用这个:http://cpp.sh/4du5

【讨论】:

    【解决方案2】:

    你读过pthreads documentation吗? pthreads 中的线程函数必须如下所示:

      void * dowork( void * arg );
    

    然后,您将函数传递给 pthread_create API,并将指针传递给您希望它处理的内容。在您的情况下,您可能希望创建一个结构来保存要处理的数据,例如:

      struct param {
            int anarray[10];
            int size;
      }
    

    然后你会以某种方式实例化结构:

      param p = { ...  };
    

    并调用 pthread 创建:

       pthread_create(&thread, NULL, dowork, & p );
    

    你的 dowork 函数将被带有结构实例地址的线程调用,你需要解包并以某种方式使用。

    如果您只使用 C++ 标准库中的 std::thread 类,所有这些都会简单得多

    【讨论】:

      猜你喜欢
      • 2012-01-19
      • 1970-01-01
      • 1970-01-01
      • 2017-12-04
      • 2011-10-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      相关资源
      最近更新 更多