如何终止pthread中的睡眠线程? [英] how to terminate a sleeping thread in pthread?

查看:317
本文介绍了如何终止pthread中的睡眠线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程睡了很长时间,然后醒来做某事,然后又睡了,就像这样:

I have thread which sleeps for a long time, then wakes up to do something, then sleep again, like this:

while(some_condition)
{
    // do something
    sleep(1000);
}

如何使该线程正常且快速退出?

How could I make this thread exit gracefully and QUICKLY?

我尝试使用pthread_cancel(),但是无法取消休眠线程. 我还尝试了更改while循环的条件,但是退出仍然需要很长时间. 而且我不想使用pthread_kill(),因为它可能在工作时杀死线程.

I tried to use pthread_cancel(), but sleeping threads could not be canceled. I also tried changing the condition of the while loop, but it will still take long to exit. And I don't want to use pthread_kill(), since it may kill the thread when it's working.

那么,有什么好主意吗?

So, are there any good ideas?

推荐答案

作为sleep的替代方案,您可以使用

As an alternative to sleep, you could use pthread_cond_timedwait with a 1000 ms timeout. Then when you want to exit, signal the condition variable.

这类似于您在C#/Java中使用等待并通知"的方式.

This is similar to how you might do this in C#/Java using wait and notify.

这篇关于如何终止pthread中的睡眠线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆