【发布时间】:2020-08-18 03:03:47
【问题描述】:
我被要求在一个进程(48)中创建一些线程,但是只有当包括它自己在内的 6 个线程正在运行时,14 号线程才能停止。然而他们进入了一个无限循环。
这是我的进程中的线程应该执行的函数:
pthread_mutex_lock_t lock;
pthread_mutex_cond_t cond;
reached_6_threads = false;
void *thread_function_P6(void *args)
{
th *t = (th *)args;
printf("started thread %d", t->id);
if (t->id != 14)
{
pthread_mutex_lock(&lock);
while (th_no > 6)
{
pthread_cond_wait(&cond, &lock);
}
if(!reached_6_threads && th_no==6){
pthread_cond_wait(&cond, &lock);
th_no--;
reached_6_threads = true;
}
th_no++;
if (!reached_6_threads && th_no == 6)
{
pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&lock);
}
}
printf("threads running: %d\n", th_no);
printf("stopped thread %d", t->id);
pthread_exit(0);
}
lock 和 cond 在创建线程之前被初始化。
【问题讨论】:
标签: c multithreading synchronization barrier