【发布时间】: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 或更高版本),请改用<thread>。这确实是现代 C++ 线程世界的晚餐。