C 仅当n个线程正在运行(包括自身)时停止线程
我被要求在一个进程(48)中创建一些线程,但14号线程必须只能在包括自身在内的6个线程正在运行时停止。然而,它们进入了一个无限循环 以下是进程中我的线程应该执行的函数:C 仅当n个线程正在运行(包括自身)时停止线程,c,multithreading,synchronization,barrier,C,Multithreading,Synchronization,Barrier,我被要求在一个进程(48)中创建一些线程,但14号线程必须只能在包括自身在内的6个线程正在运行时停止。然而,它们进入了一个无限循环 以下是进程中我的线程应该执行的函数: pthread_mutex_lock_t lock; pthread_mutex_cond_t cond; reached_6_threads = false; void *thread_function_P6(void *args) { th *t = (th *)args; p
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在创建线程之前已初始化。我不确定是否理解您的意思,但请在代码中注意: a) 大多数代码都处于互斥锁下,这意味着它们不能真正并行运行 b) 无论运行的线程数是多少,线程14都会运行 无论如何,它被卡住的原因是: a) 您的线程几乎按顺序运行 b) 线程1-5在同时跳过两个ifs时,THU no现在是5(假设它被初始化为0?) c) 线程6将THU no提升到6,并进入第二个if,执行广播,但没有线程卡在该条件锁上 d) 线程7及以上的线程首先进入if并等待一个永不中断的条件锁 我建议以下解决方案。因为我还没有完全理解您的意思,所以在这个例子中,不管它们的id如何,只允许运行6个线程,您只需要做一些小的更改
pthread_mutex_lock(&lock);
while(th_no >= 6){pthread_cond_wait(&cond, &lock);}
th_no++;
pthread_mutex_unlock(&lock); //Raise counter and unlock the mutex
/*
Thread function code here. Pay attention to critical code and use mutex.
*/
pthread_mutex_lock(&lock); //Acquire lock once again, decrease counter and broadcast if number of threads is ok now
th_no--;
if(th_no <= 5){
if(pthread_cond_broadcast(&cond)){
// Error as it should return 0 on success
}
}
pthread_mutex_lock(&unlock);
pthread\u mutex\u lock(&lock);
while(th_no>=6){pthread_cond_wait(&cond,&lock)}
th_no++;
pthread_mutex_unlock(&lock)//升起计数器并解锁互斥锁
/*
线程函数代码在这里。注意关键代码并使用互斥。
*/
pthread_mutex_lock(&lock)//再次获取锁,如果线程数现在正常,则减少计数器并广播
不;
如果(THU no Yes THU no)用0初始化,您的建议非常有用,非常感谢!