Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does boost::thread sleep() do?

I am currently working on a small wrapper class for boost thread but I dont really get how the sleep function works, this is what I have got so far:

BaseThread::BaseThread(){
    thread = boost::thread();
    bIsActive = true;
}

BaseThread::~BaseThread(){
    join();
}

void BaseThread::join(){
    thread.join();
}

void BaseThread::sleep(uint32 _msecs){
    if(bIsActive)
        boost::this_thread::sleep(boost::posix_time::milliseconds(_msecs));
}

This is how I implemented it so far but I dont really understand how the static this_thread::sleep method knows which thread to sleep if for example multiple instances of my thread wrapper are active. Is this the right way to implement it?

like image 697
user240137 Avatar asked Dec 29 '09 11:12

user240137


People also ask

What is boost thread C++?

Boost. Thread is the library that allows you to use threads. Furthermore, it provides classes to synchronize access on data which is shared by multiple threads. Threads have been supported by the standard library since C++11.

How do you make a thread sleep in C++?

C++ 11 provides specific functions to put a thread to sleep. Description: The sleep_for () function is defined in the header <thread>. The sleep_for () function blocks the execution of the current thread at least for the specified time i.e. sleep_duration.

Does thread sleep block?

Sleep method. Calling the Thread. Sleep method causes the current thread to immediately block for the number of milliseconds or the time interval you pass to the method, and yields the remainder of its time slice to another thread. Once that interval elapses, the sleeping thread resumes execution.


2 Answers

boost::this_thread::sleep will sleep the current thread. Only the thread itself can get to sleep. If you want to make a thread sleep, add some check code in the thread or use interruptions.

UPDATE: if you use a c++11 compiler with the up to date standard library, you'll have access to std::this_thread::sleep_for and std::this_thread::sleep_until functions. However, there is no standard interruption mechanism.

like image 172
Klaim Avatar answered Oct 28 '22 14:10

Klaim


sleep always affects current thread (the one that calls the method).

like image 26
Benoît Avatar answered Oct 28 '22 12:10

Benoît