线程障碍。线程 T6.13 只能在 6 个线程(包括其自身)运行时结束

问题描述 投票:0回答:1

• 进程的主线程,即 T6.0 不得在其他 43 个线程之前终止。

• 任何时候,进程P6最多可以有6个线程同时运行,不包括主线程。

我的代码需要通过一些测试。在某一点上,显示停止并进入无限循环。

TH_STRUCT_2 *param = (TH_STRUCT_2*)arg;

sem_wait(param->semaphore);

pthread_mutex_lock(param->lock);
(*param->active_threads)++;
int thread_num = param->thread_num;
pthread_mutex_unlock(param->lock); 

sem_post(param->start_semaphore); 

info(BEGIN, 6, thread_num);

if(thread_num == 13) {
    printf("%d\n", (*param->active_threads) );
    pthread_mutex_lock(param->lock);
    while(*param->active_threads < 6) {
        pthread_cond_wait(param->cond, param->lock);
    }
    pthread_mutex_unlock(param->lock);
}

pthread_mutex_lock(param->lock);
(*param->active_threads)--;
pthread_mutex_unlock(param->lock);

info(END, 6, thread_num); 

if(thread_num == 13 && *param->active_threads == 1) {
    pthread_cond_broadcast(param->cond); 
}

sem_post(param->semaphore); 

return NULL;
c pthreads
1个回答
0
投票

pthread_cond_broadcast() 由线程 num 13 执行,如果它在 pthread_cond_wait() 中等待,则广播永远不会发生。没有显示如何启动线程的代码。如果它们在终止后连续创建,那么在某个点 num 13 线程将继续等待,并且稍后不会创建它,并且不会有广播。可以在 cond_wait() 中检查 13 是否不等待

    while(thread_num != 13 && *param->active_threads < 6) {

另一个问题是 thread_num 对于所有线程都是通用的,假设每个线程启动都重用参数。那么thread_num就会出现竞争条件。例如,如果启动了 5 个线程,并且它们将在不同时间点访问 param->thread_num,那么很少有线程会得到错误的线程号。除了线程 13 持有 cond_broadcast() 之外,这并不是什么大问题

© www.soinside.com 2019 - 2024. All rights reserved.