【发布时间】:2014-03-18 04:59:17
【问题描述】:
我正在尝试使用 pthread_barrier_wait() 来同步线程,但如果 MAIN 中的 LOOP 迭代次数超过 1,则线程不会同步。这里 (s
谢谢。
这是我的代码:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#define ARRAYSIZE 6
#define NUMTHREADS 3
using namespace std;
// Barrier variable
pthread_barrier_t barr;
unsigned int count = NUMTHREADS;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct ThreadData {
int start, stop, tid;
};
void* squarer(void* td) {
struct ThreadData* data=(struct ThreadData*) td;
int start=data->start;
int stop=data->stop;
int tid = data ->tid;
int i,s;
//MAIN LOOP
for (s=0; s<2; s++){
for (i=start; i<stop; i++) {
printf("thread no. %d is writing: \n", tid);
}
// Synchronization point
int rc = pthread_barrier_wait(&barr);
if(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD){
printf("Could not wait on barrier\n");
exit(-1);
}
for (i=start; i<stop; i++) {
printf("thread no. %d is executing: \n", tid);
}
}
return NULL;
}
int main(void) {
pthread_t thread[NUMTHREADS];
struct ThreadData data[NUMTHREADS];
// Barrier initialization
if(pthread_barrier_init(&barr, NULL, NUMTHREADS)){
printf("Could not create a barrier\n");
return -1;
}
int i;
int tasksPerThread=(ARRAYSIZE+NUMTHREADS-1)/NUMTHREADS;
/* Divide work for threads, prepare parameters */
for (i=0; i<NUMTHREADS; i++) {
data[i].start=i*tasksPerThread;
data[i].stop=(i+1)*tasksPerThread;
data[i].tid = i;
}
/* the last thread must not go past the end of the array */
data[NUMTHREADS-1].stop=ARRAYSIZE;
/* Launch Threads */
for (i=0; i<NUMTHREADS; i++) {
pthread_create(&thread[i], NULL, squarer, &data[i]);
}
/* Wait for Threads to Finish */
for (i=0; i<NUMTHREADS; i++) {
pthread_join(thread[i], NULL);
}
return 0;
}
这是输出:
线程编号。 2 正在写作:
线号2 正在写作:
线号0 正在写:
线号0 正在写:
线号1 正在写作:
线号1 正在写作:
线号1 正在执行:
线号1 正在执行:
线号1 正在写作:
线号1 正在写作:
线号0 正在执行:
线号0 正在执行:
线号0 正在写:
线号0 正在写:
线号2 正在执行:
线号2 正在执行:
线号2 正在写作:
线号2 正在写作:
线号2 正在执行:
线号2 正在执行:
线号0 正在执行:
线号0 正在执行:
线号1 正在执行:
线号1 正在执行:
【问题讨论】:
标签: multithreading parallel-processing pthreads posix