在时间到期之前唤醒pthread_cond_timedwait()
在我的项目中,我正在尝试使用条件变量同步多个线程。每个运动都需要在给定的时间内睡觉。例如,线程A 更改数据,然后必须睡15秒。我用pthread_cond_timedwait()完成了这个定时的睡眠时间,因为睡眠的行为()是未预测的,而不是稳定的。
但是,在某些情况下,我必须在时间到期之前唤醒所有线程。假设该线程A当前正在睡15秒钟,相对时间在第二7秒。当我使用pthread_cond_broadcast()或pthread_cond_signal()在15秒到期之前唤醒线程A时,它不会反映。有没有与此问题有关的解释?我可以在时间到期之前发出定时条件变量吗?
伪代码如下:
vector<pthread_cond_t> cond_list;
void signal_control_function() {
// this function keeps track of time and send wake-up signals by looping
if (time == SIGNAL_TIME) {
for (int i = 0; i < cond_list.size(); i++) {
pthread_cond_broadcast(&cond_list[i]);
}
}
}
void* thread_function(void* arg) {
pthread_cond_t cv;
cond_list.pus_back(cv);
for (int i = 0; i < 100; i++) {
// make change
// set up time variable
pthread_cond_timedwait(&cv, &mutex, &time)
}
}
谢谢。
In my project, I'm trying to synchronize multiple threads using the condition variables. Each thread needs to sleep for a given amount of time for each movement. For example, after Thread A changes the data and then it must sleep for 15 seconds. I accomplished this timed sleeping with pthread_cond_timedwait() since the behavior of sleep() is unpredicted and not stable.
However, I have to wake up all threads before time expires in some cases. Suppose that Thread A is currently sleeping for 15 seconds and relative time is at second 7. When I use pthread_cond_broadcast() or pthread_cond_signal() to wakeup Thread A before 15 second expires, it does not reflect. Is there any explanation related to this issue? Can I signal the timed condition variable before its time expires?
Pseudocode is like following:
vector<pthread_cond_t> cond_list;
void signal_control_function() {
// this function keeps track of time and send wake-up signals by looping
if (time == SIGNAL_TIME) {
for (int i = 0; i < cond_list.size(); i++) {
pthread_cond_broadcast(&cond_list[i]);
}
}
}
void* thread_function(void* arg) {
pthread_cond_t cv;
cond_list.pus_back(cv);
for (int i = 0; i < 100; i++) {
// make change
// set up time variable
pthread_cond_timedwait(&cv, &mutex, &time)
}
}
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论