简体   繁体   English

当线程/进程处于睡眠状态时,睡眠线程或进程的指令是否继续执行?

[英]Does an instruction of sleep thread or process continues its execution while the thread/process is slept?

When i do my assignment on IPC(Inter Process Communication),a chat application using shared memory between two process,how does a sleep thread checks the condition in the while loop(if *shm != 1 the thread prints the string wakeup) how can is this possible? 当我在IPC(进程间通信)上进行分配时,一个使用两个进程之间共享内存的聊天应用程序,睡眠线程如何检查while循环中的条件(如果* shm!= 1,则该线程将打印字符串唤醒)这可能吗?

#define TRUE 1

while(*shm == 1)
    sleep(1)
printf("wakeup");

The sleep doesn't check shm value. sleep不检查shm值。

Right now your thread calls sleep , it will suspend the thread just for a few miliseconds, and then it will be woken up by a signal from OS timer/scheduler. 现在,您的线程调用sleep ,它将使线程暂停几毫秒,然后由OS计时器/调度程序发出的信号将其唤醒。 That's all that sleep does. 这就是sleep要做的。 Then the thread wakes up and resumes your code: sleep() returns, loop starts next iteration, checks shm and makes a decision whether to sleep again or continue. 然后线程唤醒并继续您的代码:sleep()返回,循环开始下一次迭代,检查shm并决定是否再次休眠或继续。

It works, but consumes more than it could if you've used specialized synchronization primitives - like condition variables in c++11/posix. 它可以工作,但是比使用专门的同步原语(例如c ++ 11 / posix中的条件变量)消耗更多的钱。 Sleeping while waiting for condition variable signal will truly sleep until signal is received, without wasting cpu cycles for such periodical wake-ups. 在等待条件变量信号时休眠将真正休眠,直到接收到信号为止,而不会浪费此类周期性唤醒的cpu周期。

unsigned int sleep(unsigned int seconds);

Suspends thread execution for a specified number of seconds. 将线程执行挂起指定的秒数。 Because of processor delays, the thread can sleep slightly longer than this specified time. 由于处理器延迟,线程可以比此指定时间稍长的睡眠时间。 An unblocked signal received during this time (for which the action is to invoke a signal handler function or to end the thread) “wakes up” the thread prematurely. 在此期间接收到的无阻塞信号(其动作是调用信号处理程序功能或结束线程)会过早地“唤醒”线程。 When that function returns, sleep() returns immediately even if there is sleep time remaining. 当该函数返回时,即使有剩余的睡眠时间,sleep()也会立即返回。

So your while(*shm == 1) doesn't calcs while thread sleeps. 因此while(*shm == 1)当线程休眠时,您的while(*shm == 1)不会计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM