gpt4 book ai didi

c - 如何停止和继续 pthread?

转载 作者:太空狗 更新时间:2023-10-29 16:52:24 24 4
gpt4 key购买 nike

我正在用 C 编写代码(实际上是在 OOC 中,然后编译为 C)。

如何指示线程在特定检查点等待,直到其他线程告诉它继续?

我实际上在线程中使用了一个紧密循环并轮询了一个我从主线程更改的变量,但我认为这不是很好,对吗?除此之外,当我在线程中进行紧密循环时,我是否应该在循环中加休眠眠以避免仅循环消耗大量 CPU 功率?

最佳答案

看来你在找pthread_cond_wait及其相关功能。

这是来自 manpage 的引述举个例子:

Consider two shared variables x and y, protected by the mutex mut, and a condition variable cond that is to be signaled whenever x becomes greater than y.

          int x,y;
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

Waiting until x is greater than y is performed as follows:

          pthread_mutex_lock(&mut);
while (x <= y) {
pthread_cond_wait(&cond, &mut);
}
/* operate on x and y */
pthread_mutex_unlock(&mut);

Modifications on x and y that may cause x to become greater than y should signal the condition if needed:

          pthread_mutex_lock(&mut);
/* modify x and y */
if (x > y) pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mut);

最后它完成了您的要求:调用 pthread_cond_wait(&cond) 的线程被阻塞,直到另一个线程(例如您的主线程)调用 pthread_cond_broadcast(&cond)。在此期间它只是处于 blocked 状态并且不消耗 CPU 周期。

关于c - 如何停止和继续 pthread?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4794940/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com