【问题标题】:Unable to synchronize posix pthreads using pthread_barrier_wait()无法使用 pthread_barrier_wait() 同步 posix pthread
【发布时间】: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


    【解决方案1】:

    鉴于您编写的代码,该输出可以很好地同步。在所有线程完成“写入”步骤之前,没有线程开始“执行”步骤。

    此外,如果您希望在所有线程完成上一个“执行”步骤之前没有线程开始下一个“写入”步骤,则需要在“执行”步骤之后额外调用 pthread_barrier_wait()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-10-01
      • 1970-01-01
      • 2012-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      相关资源
      最近更新 更多