在时间到期之前唤醒pthread_cond_timedwait()

发布于 2025-01-31 08:56:22 字数 949 浏览 2 评论 0原文

在我的项目中,我正在尝试使用条件变量同步多个线程。每个运动都需要在给定的时间内睡觉。例如,线程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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文