[英]How to avoid waiting for pthread_cond_t where signal already sent
I've got a logic inside a dynamic library that run some service that is requested by the main executable. 我在动态库中有一个逻辑,该逻辑可以运行主要可执行文件请求的某些服务。
Upon calling start_service
from the library code, some preparation is required prior to service ready, and during this time, the main code should not try to access the service. 从库代码调用
start_service
,需要在进行服务准备之前进行一些准备工作,在此期间,主代码不应尝试访问该服务。
To notify the main code when the service is ready I use conditional variable and signal the main executable. 为了在服务就绪时通知主代码,我使用条件变量并向主可执行文件发出信号。
I'd like to hear some advices about the best way to handle a situation when the library become serviceable BEFORE the main code wait for the conditional variable. 我想听听一些有关在库在主代码等待条件变量可用之前就可以使用的最佳处理方式的建议。 in this case, the waiting can last forever...
在这种情况下,等待可以永远持续下去...
here's the service code : 这是服务代码:
extern pthread_cond_t cnd;
extern pthread_mutex_t mtx;
void start_service()
{
// getting serviceable.
pthread_cond_signal(&cnd);
main_loop();
}
And here's the main code. 这是主要代码。
pthread_cond_t cnd;
pthread_mutex_t mtx;
int main()
{
pthread_cond_init(&cnd,NULL);
pthread_mutex_init(&mtx, NULL);
std::thread mytrd(&start_service);
...
pthread_mutex_lock(&mtx);
pthread_cond_wait(&cnd, &mtx); // what happens if we get here after the signal already sent.
pthread_mutex_unlock(&mtx);
...
}
PS the desired behavior should be that the main code avoid waiting for the conditional variable if it's already signaled. PS期望的行为应该是主代码避免等待条件变量(如果已发出信号)。
You need a predicate and enclose the wait
in a check for the predicate: 您需要一个谓词并将
wait
时间包含在该谓词的检查中:
pthread_mutex_lock(&mtx);
while( ! predicate ) pthread_cond_wait(&cnd, &mtx);
pthread_mutex_unlock(&mtx);
In this way, the thread doesnt event start to wait when it doesnt need to. 这样,线程的not事件在不需要时就开始等待。 The second reason you need this is to avoid spurious wakeups thay may occur, ie
pthread_cond_wait
may return even if the other thread did not signal the condition. 您需要这样做的第二个原因是为了避免发生虚假的唤醒,即即使另一个线程未发出信号通知
pthread_cond_wait
也可能返回。
The other thread then has to do (you need to lock the mutex to protect the predicate): 然后,另一个线程必须做(您需要锁定互斥量以保护谓词):
pthread_lock_mutex(&mtx);
predicate = true;
pthread_cond_signal(&cnd);
pthread_unlock_mutex(&mtx);
You can use a semaphore with initial count of 0
, so main
gets blocked, until start_service()
increase semaphore count to 1
.If before the block call in main
, start_service()
increases the semaphore count to 1
, main will never enter into wait state.Something like below. 您可以使用初始计数为
0
的信号量,这样main
就会被阻塞,直到start_service()
将信号量计数增加到1
如果在main
的块调用之前, start_service()
将信号量计数增加到1
,则main将永远不会进入等待状态状态。如下所示。
void start_service()
{
// getting serviceable.
sem_post(&sem_mutex);//increases to 1
main_loop();
}
int main()
{
sem_init(&sem_mutex, 0, 0);//initially blocked.
std::thread mytrd(&start_service);
sem_wait(&sem_mutex);
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.