C++ pthread 睡眠 linux

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3633089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 13:20:07  来源:igfitidea点击:

pthread sleep linux

c++multithreadingpthreads

提问by Steveng

I am creating a program with multiple threads using pthreads.

我正在使用 pthreads 创建一个具有多个线程的程序。

Is sleep()causing the process (all the threads) to stop executing or just the thread where I am calling sleep?

sleep()导致进程(所有线程)停止执行还是只是我正在调用的线程sleep

回答by caf

Just the thread. The POSIX documentation for sleep()says:

只是线程。sleep()POSIX 文档说:

The sleep()function shall cause the calling threadto be suspended from execution...

sleep()函数应导致调用线程暂停执行...

usage: sleep(10)for 10 seconds sleep.

用法:sleep(10)睡眠10秒。

回答by Chand Priyankara

Try this,

尝试这个,

#include <unistd.h>

usleep(microseconds);

回答by CMorgan

I usually use nanosleepand it works fine. Nanosleep supends the execution of the calling thread. I have had the same doubt because in some man pages sleep refers to the entire process.

我通常使用nanosleep并且它工作正常。Nanosleep 会暂停调用线程的执行。我也有同样的疑问,因为在某些手册页中 sleep 指的是整个过程。

回答by Ricky

sleep()function does not cease a specific thread, but it stops the whole process for the specified amount of time. For stopping the execution of a particular thread, we can use one pthread condition object and use pthread_cond_timedwait()function for making the thread wait for a specific amount of time. Each thread will have its own condition object and it will never receive a signal from any other thread.

sleep()函数不会停止特定线程,但会在指定的时间内停止整个进程。为了停止特定线程的执行,我们可以使用一个 pthread 条件对象并使用pthread_cond_timedwait()函数使线程等待特定时间。每个线程都有自己的条件对象,它永远不会从任何其他线程接收信号。