What does boost::thread sleep() do?
Asked Answered
P

2

12

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?

Prayerful answered 29/12, 2009 at 11:29 Comment(0)
M
17

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.

Mayer answered 29/12, 2009 at 11:31 Comment(2)
check code like what? interruptions seems to be a good way too.Prayerful
What i mean by "check code" is that in the code executed by the given thread, somewhere there is a 'if' that checks if it needs to be slept and do it if necessary. For example if your thread runs a function with a big loop, then checking if it needs to sleep (by checking a boolean set by your current code for example) at each end of iteration of the loop might be enough. But in your case you don't want to be intrusive to your thread code so interruptions seems like a really better alternative.Mayer
A
2

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

Ankus answered 29/12, 2009 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.