示例代码如何使用pthread暂时挂起线程。 [英] Sample code How to suspend a thread temporarily using pthread.

查看:692
本文介绍了示例代码如何使用pthread暂时挂起线程。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是多线程编程的新手。有一个要求像这样的东西。假设我有一个按钮(播放和暂停)播放意味着它继续播放或暂停意味着它必须暂停

解决方案

POSIX线程已有详细记录。例如,参见POSIX线程编程 [ ^ ],可能条件变量符合您的需求。


通常是什么你想做的是检查新线程中的变量/条件并采取相应的行动。



  //  伪代码 
thread_executor(...)
{
while (运行){
如果(暂停)继续;
其他 {
// 做工作......
}
}
}





有一些允许线程外部暂停的线程实现,但它不是推荐或理想的做法,因为它使线程内存和访问器处于未定义状态(即你在该线程中使用的变量会发生什么?如果你锁定了什么一个带有互斥的共享内存位置?)。





编辑:有一些线程实现(无法回想起哪一个这会导致紧密循环占用大量处理器时间(即上面的继续声明)。在这些情况下,您还可以通过休眠一段时间来节省一些周期(即 if(pause)sleep(10))。或者,您可以使用控制信号(在Windows中,查找 WaitForSingleObject()),但一定要使用超时,这样就不会锁定线程。


I am new to the multi threaded  programming . there is a requirement some thing like this.Suppose I have a button (play and Pause) play means its continues play going on or pause means it have to pause

解决方案

POSIX threads are well documented. See for instance "POSIX Threads Programming"[^], possibly condition variables fit your needs.


Typically what you would want to do is check a variable/condition within your new thread and act accordingly.

//pseudo-code
thread_executor(...)
{
  while(run){
    if(pause) continue;
    else{ 
       //do work...
    }
  }
}



There are some thread implementations that allow for external suspension of a thread but its not a recommended or ideal practice because it leaves the thread memory and accessors in an undefined state (i.e. what happens to the variables that you're using within that thread? what if you locked a shared memory location with a mutex?).


edit: There are some thread implementations (can't recall which one off the top of my head) that would lead a "tight" loop into taking up a lot of processor time (i.e. the continue statement above). In those cases, you can also save some cycles by sleeping for some period of time (i.e. if(pause) sleep(10)). Alternatively, you can use a control signal (in Windows, look up WaitForSingleObject()), but be sure to use timeouts so you don't lock up threads.


这篇关于示例代码如何使用pthread暂时挂起线程。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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