What does boost::thread sleep() do? - c++

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?

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.

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

Related

Multithreading a while loop in c++

I've started c++ (coming from a c# background), and in my program I need to run a while true loop, but since it is an imgui program the ui freezes up completely since I'm using Sleep() in the loop. I need to create a new thread but everything I've found online is just
std::thread nThread(Method);
nThread.join();
Now, the issue with this is it doesn't work at all since, I'm assuming, it's a while loop that's always running. I want to do the c++ equivalent of Thread thread = new Thread(method) and thread.Start(); in c#. If anyone can help me, I'd appreciate it.
t.join() waits for thread t to die. If you don't want the method that started the thread to wait for it, then don't join() it.
But note! The C++ library will get angry with you if you allow the thread object to be destroyed while the thread still is running. (The destructor will throw an exception.) If you want to tell the library, "Shut up! I know what I'm doing," you can detach the thread from the object. But usually it's a cleaner design if you can arrange for the object to live for as long as you need the thread to run.
Try a simple example and work from there.
void myFunc()
{
try
{
int x = 0;
while (x < 10)
{
sleep(1000);
std::cout<<"Thread is running"<<std::endl;
x++;
}
}
catch(Interrupted_Exception&) {
cout << "Caught Interrupted_Exception" << endl;
}
}
int main()
{
std::cout<<"Starting main"<<std::endl;
std::thread nThread(myFunc);
std::cout<<"Thread is running. Waiting for it to complete"<<std::endl;
nThread.interrupt();//in case the thread is sleeping
nThread.join();
std::cout<<"All done. Exiting"<<std::endl;
return 0;
}
Join means that the main thread has to wait for the worker thread. It's a way to ensure that the worker thread terminates before the caller. You only want to do that when you are terminating the program, in your case when the GUI is being close. Since at that time you want to tell the worker thread to stop right away, you call interrupt() on tell it to stop sleeping.
In the example, you can comment out the interrupt call so that the worker thread runs to completion.
There is no direct equivalent of that in the standard C++ library. When you use std::thread, the new thread starts immediately. You can simulate delayed start behaviour by making the thread stuck on a locked in advance mutex, then release mutex when you want the thread action to run actually. Aftwerwards you have to either join the thread or make it detached, otherwise std::thread destructor will throw an exception.
If you are on Windows, you can try to use Windows API directly (CreateThread() with flag CREATE_SUSPENDED, then ResumeThread() and finally posssibly TerminateThread() - if thread has sort of endless loop which never terminates in itself).
There is a way you can approach this and is using std::future and std::async with std::launch::async mode and throwing the function with the loop there.
std::future allows you to run a thread in the background and then after running give back the control to the parent thread so the program's flow can go as normal.
so you could have a boolean for the while and when std::future gives you back the control then you could modify this bool in the parent or main thread.

How to stop a running parallel thread with C++ on Mac?

I’ve been looking for an answer, and indeed found some possible ways to stop a running parallel thread with C++, but the solutions would usually apply only on Windows (for instance, the TerminateThread() function ). Is there a way to stop a running parallel thread on Mac (I’m using CodeBlocks) ?
A typical clean/safe setup might be....
std::atomic<bool> exit{false};
std::thread thread([&]{
while (!exit) { /* do stuff */ }
});
// later, when you want to exit:
exit = true;
// `join` before the `thread` object goes out of scope
thread.join();
From this you can probably see there are endless ways to tell your thread to stop running and end cleanly. Just make sure whatever you way you use is thread safe (either atomic or protected by a mutex) and make sure you call thread.join() before the thread object goes out of scope, or any time you wish to block waiting for the thread to finish.

Deferred function call in C/C++

How can I call a function in C++ after a certain period of time or at a particular time?
I searched in Google and in Stackoverflow. I only found way to do this through SIGALARM handler.
Update 1:
P.S. I use Linux.
P.P.S. I haven't got any written code, because I want to know how to do that, before writing.<
You'd probably want to do that in another throwaway thread, as waiting in the main thread would block your app. You can add the delay in that thread by using std::this_thread::sleep_for.
I.e.
using namespace std;
thread([]{this_thread::sleep_for(chrono::milliseconds(1000)); foo(); }).detach();
The POSIX way of doing it in C is through setting a signal handler with SIGALARM and having in it the function that you want to be called. In this scenario, you give to the operative system (kind of) the responsibility to call you once the time has come.
The C++11 way of doing it is through std::thread and std::chrono. A very simple, and may be not complete example:
std::chrono::milliseconds duration( 2000 );
auto deferred_task = [duration] () { std::this_thread::sleep_for(duration); call_task(); }
std::thread t(deferred_task);
In this barebone exmple your program is multithreading, and one thread is responsible to make the deferred call (in another thread). You may want to join, to catch a return value, and whatever you want, synchronously or asynchronously.
You want to have a multithread application or do you require a single-thread signal C behaviour? This is quite critical and it will be your main constraint on your code style from here.
Try the answer to this question if you have access to the Boost libraries. You can either call your function periodically or as a one-off.
Try to use timer. Or in linux use epoll. And something like waitforsingleobject in Windows.
You can actually do it in a super simple way:
void example(void (*f)()) {
struct defer {
void (*f)();
~defer() { f(); }
} _[[maybe_unused]] { f };
}

Semaphore (Mutex) trouble

Let's say I have one Mutex, two threads, one function and one cycle (Pseudo code).
Function:
void Update(){
Mutex.enter();
...// time: 10 ms
Mutex.leave();
}
Main.cpp:
void main(){
...// Starting thread
while(true)
Update();
}
Thread:
void Thread(void *){
Mutex.enter();
... //
Mutex.leave();
}
But Function calls constantly, so Mutex small time is free. How high chance Thread have to enter in Mutex? If low, how it can be resolved?
If you're using boost threads (link), then I'd use yield(). It'll allow any other "waiting" threads to "get a chance" to run.
There's probably a win32 or pthreads way of doing this too.
Edit: and by the way, use yield() outside of the locks. If it's inside the locks, obviously that would be useless.
Edit2: And here's the functions for different platforms:
Win32: SwitchToThread() msdn link.
Linux/Unix pthreads: `pthread_yield()' link
If you're not on any of those platforms, read the descriptions at those links, and look for a function that does the same thing in your framework.
From the pseudo-code you showed it seems like there's no cooperation between threads. If thread2 is lucky to grab the mutex before the call to the first Update() is placed then for the whole lifetime of thread2 Update() functions will not be called. It looks like a flawed design to me. If thread2 is doing the work and 'main' thread is calling Update() function to monitor and report the progress of whatever is happening in thread2 thread routine, then it would make much more sense to have thread1 (the main one) wait on a update_required signal and thread2 (the one that is progressing with work) would do the work, then fill-in a struct variable with all the data needed to report the progress and signal thread1 to use the data and report the progress. Using a ring buffer of such struct variable could eliminate the need for mutexes altogether.

How Operating System callbacks work

Follow up question to:
This question
As described in the linked question, we have an API that uses an event look that polls select() to handle user defined callbacks.
I have a class using this like such:
class example{
public:
example(){
Timer* theTimer1 = Timer::Event::create(timeInterval,&example::FunctionName);
Timer* theTimer2 = Timer::Event::create(timeInterval,&example::FunctionName);
start();
cout<<pthread_self()<<endl;
}
private:
void start(){
while(true){
if(condition)
FunctionName();
sleep(1);
}
}
void FunctionName(){
cout<<pthread_self()<<endl;
//Do stuff
}
};
The idea behind this is that you want FunctionName to be called both if the condition is true or when the timer is up. Not a complex concept. What I am wondering, is if FunctionName will be called both in the start() function and by the callback at the same time? This could cause some memory corruption for me, as they access a non-thread safe piece of shared memory.
My testing tells me that they do run in different threads (corruption only when I use the events), even though: cout<<pthread_self()<<endl; says they have the same thread id.
Can someone explains to me how these callbacks get forked off? What order do they get exectued? What thread do they run in? I assume they are running in the thread that does the select(), but then when do they get the same thread id?
The real answer would depend on the implementation of Timer, but if you're getting callbacks run from the same thread, it's most likely using signals or posix timers. Either way, select() isn't involved at all.
With signals and posix timers, there is very little you can do safely from the signal handler. Only certain specific signal safe calls, such as read() and write() (NOT fread() and fwrite(), or even new and cout) are allowed to be used. Typically what one will do is write() to a pipe or eventfd, then in another thread, or your main event loop running select(), notice this notification and handle it. This allows you to handle the signal in a safe manner.
Your code as written won't compile, much less run. Example::FunctionName needs to be static, and needs to take an object reference to be used as a callback function.
If the timers run in separate threads, it's possible for this function to be called by three different threads.