我在C++中唤醒线程时遇到问题。我有4个正在运行的线程。我想在4个正在运行的线程完成后唤醒我的睡眠线程。我做了条件等待手术,但看起来不太好。如何以更高质量的方式完成此过程?
4个任务由广播触发,并同时开始在不同的核心上工作。在每个任务结束时,它将自己的taskID的标志设置为1,并向睡眠任务发送信号。处于睡眠状态的任务每次收到信号时都会唤醒,并检查每个任务的标志。如果4任务标志为1,它将继续并执行自己的工作。
void *thread_sleep( void *arg )
{
pthread_mutex_lock(&mutex_sleep);
while(flag_task[0] == 0 || flag_task[1] == 0 || flag_task[2] == 0 || flag_task[3] == 0)
pthread_cond_wait(&cond_sleep, &mutex_sleep);
/*
.
.
.
.
*/
flag_task[0] = 0;
flag_task[1] = 0;
flag_task[2] = 0;
flag_task[3] = 0;
pthread_mutex_unlock(&mutex_sleep);
}
void *thread( void *arg)
{
int taskID = *(char *)arg - '0';
while(1)
{
pthread_mutex_lock(&mutex[taskID]);
pthread_cond_wait(&cond, &mutex[taskID]);
/*
.
.
.
.
*/
pthread_mutex_unlock(&mutex[taskID]);
flag_task[taskID] = 1;
pthread_cond_signal(&cond_sleep);
}
}
int main()
{
pthread_create( &pthread1, NULL, thread, (void *)"0" );
pthread_create( &pthread2, NULL, thread, (void *)"1" );
pthread_create( &pthread3, NULL, thread, (void *)"2" );
pthread_create( &pthread4, NULL, thread, (void *)"3" );
pthread_create( &pthread5, NULL, thread_sleep, (void *)"4" );
pthread_cond_broadcast(&cond);
}
我使用屏障解决了问题。谢谢你@Quimby。
void *thread_sleep( void *arg )
{
pthread_mutex_lock(&mutex_sleep);
pthread_cond_wait(&cond_sleep, &mutex_sleep);
/*
.
.
.
.
*/
pthread_mutex_unlock(&mutex_sleep);
}
void *thread( void *arg)
{
int taskID = *(char *)arg - '0';
while(1)
{
pthread_mutex_lock(&mutex[taskID]);
pthread_cond_wait(&cond, &mutex[taskID]);
/*
.
.
.
.
*/
pthread_mutex_unlock(&mutex[taskID]);
pthread_barrier_wait(&barrier);
pthread_cond_signal(&cond_sleep);
}
}
int main()
{
pthread_barrier_init(&barrier, NULL, 4);
pthread_create( &pthread1, NULL, thread, (void *)"0" );
pthread_create( &pthread2, NULL, thread, (void *)"1" );
pthread_create( &pthread3, NULL, thread, (void *)"2" );
pthread_create( &pthread4, NULL, thread, (void *)"3" );
pthread_create( &pthread5, NULL, thread_sleep, (void *)"4" );
sleep(1);
pthread_cond_broadcast(&cond);
}