在我的程序中,主线程创建了4个(或更多)工作线程。在某个时刻,父线程必须等待工作线程完成一些计算。这些线程在无限循环中运行,因此我不能使用pthread_join(.., ..)
POSIX函数来等待工作线程完成。所以我使用了一个全局计数器和一个条件变量。
主线程代码
unsigned jobs = 0; // global variable
// global mutex and cv. They get initialised in my main.
pthread_mutex_t counter_mutex;
pthread_cond_t counter_cv;
static void process(..){
jobs = myArray.size();
// I am using a function here that broadcasts a cv in order to
// wake up the workers
pthread_mutex_lock(&counter_mutex); // lock counter
while (jobs > 0){
pthread_cond_wait(&counter_cv, &counter_mutex); // PARENT SHOULD GET STUCK HERE TILL WORKERS ARE DONE
}
// cout << "Workers are done" << endl;
pthread_mutex_unlock(&counter_mutex); // unlock counter
}
工作线程代码
extern unsigned jobs;
extern pthread_mutex_t counter_mutex;
extern pthread_cond_t counter_cv;
void *run() {
for (int i = 0;; i++) {
// do some calculations here
pthread_mutex_lock(&counter_mutex); // lock counter
jobs--;
if (jobs == 0){
pthread_cond_signal(&counter_cv);
cout << "All jobs are done" << endl;
}
pthread_mutex_unlock(&counter_mutex); // unlock counter
}
}
问题在于有时我的主线程不会被阻塞在条件变量上等待工作线程,这导致有时会出现分段错误。是否存在我看不到的竞争条件导致了这个问题?