我需要一个同步点,而主线程以外的所有线程都被阻止(例如,监听条件)。
void *threads(void *arg){
while(true){
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond,&mutex);
//check bus
//do some work
pthread_mutex_unlock(&mutex);
}
}
int main(){
for(int i=0;i<THREAD_NUM;i++){
pthread_create(&tid[i],NULL,threads,(void*)i);
}
//write to bus
pthread_cond_broadcast(&cond);
//write to bus
pthread_cond_broadcast(&cond);
//write to bus
pthread_cond_broadcast(&cond);
}
你会怎么做?
答案 0 :(得分:0)
使用整数,互斥锁和条件变量。将整数设置为您需要等待的线程数。线程完成后,使用以下逻辑:
在代码中:
pthread_mutex_lock (mutex);
thread_count--;
while (thread_count != 0)
pthread_cond_wait (cond, mutex);
pthread_cond_broadcast (cond);
pthread_mutex_unlock (mutex);