【问题标题】:Stopping a group of threads and then letting them all go停止一组线程,然后让它们全部离开
【发布时间】:2021-01-26 03:20:50
【问题描述】:
void * worker(void * arg){
    threadData * p = (threadData *)arg; // Has thread info like what spots in the array this thread should change
    rowHead * row_head = p->info; // Has what rows need to mutiplied and which ones subtracted from
    pthread_cond_wait(&no_task_cond, &no_task_mutex); // Wait for new data to be added.
    pthread_mutex_unlock(&no_task_mutex); // Instantly give up lock since there is no critical data to protect
    pthread_cond_broadcast(&no_task_cond);
    // Go through the tasks and complete them
    rowNode * row_info = row_head->head;
    while(row_info != NULL){ // If we have a task then execute
        thread_multiplication(p->rank, p->t_row, row_info->row, row_info->multi, row_info->sub_row, p->dim, *p->matrix);
        row_info = row_info->next;
    }
    return 0;
}

我希望一组线程进入工作线程。等待所有任务都加入到链表 row_info 中,一旦主线程调用 p_thread_broadcast(&no_task_mutex) 唤醒所有线程,在退出函数之前遍历链表并执行它们的任务。

我不确定,但我很确定它在一开始就卡在等待条件上,这对我来说毫无意义,因为它应该总是至少调用一次 p_thread_broadcast。这可能与我的等​​待和广播有关,因为它们似乎并没有像我认为的那样工作。当我有一个 cond_wait 并调用一个应该唤醒所有线程的广播时,如果它们立即放弃锁,它们应该同时进行,对吗?特别是如果我之后添加了广播以确保安全

【问题讨论】:

    标签: c pthreads


    【解决方案1】:

    pthread_cond_timedwait()pthread_cond_wait() 函数应 阻塞条件变量。 应用程序应确保 这些函数由调用线程调用 互斥锁 ; 否则,一个错误(PTHREAD_MUTEX_ERRORCHECK 和健壮的互斥锁) 或未定义的行为(对于其他互斥体)结果。

    现在...您在调用pthread_cond_wait之前在哪里锁定了互斥锁?

    【讨论】:

    • 我从不这样做。我只是假设它在发出信号时锁定了互斥锁。如果我在等待之前锁定互斥锁,然后放弃锁定,它会正常运行吗?
    • 好吧,问题是您的主线程如何知道 任何 线程正在等待条件...
    • @dmb1o3:条件变量不应该在没有predicate 的情况下使用。所有对谓词的访问都应受到互斥锁的保护。您是使用谓词还是仅使用条件变量本身进行线程间通信?
    • @AndreasWenzel 我只使用条件变量本身。我会给你发送的链接阅读。
    • @dmb1o3:我给你的链接只是为了解释“谓词”这个词。我认为您需要更多地了解条件变量的用途和用法。我相信维基百科对此有a good article。不过,您或许可以使用 Google 找到更好的教程。
    猜你喜欢
    • 2018-11-03
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多