Terminate current thread in destructor - c++

In a project we're creating multiple statemachines in a wrapper-class. Each wrapper runs in it's own thread. When the jobs is done, the wrapper-class destructor is being called, and in there we would like to stop the thread.
Though if we're using thread.join(), we get a deadlock (since it tries to join itself). We could somehow signal another thread, but that seems a bit messy.
Is there any way to properly terminate the thread in which a class is running in, upon object destruction?

thread.join() does not stop a thread. It waits for the thread to finish and then returns. In order to stop a thread you have to have some way of telling the thread to stop, and the thread has to check to see whether it's time to stop. One way to do that is with an atomic bool:
class my_thread {
public:
my_thread() : done(false) { }
~my_thread() { done = true; thr.join(); }
void run() { thread th(&my_thread::do_it, this); swap(th, thr); }
private:
void do_it() { while (!done) { /* ... */ } }
std::thread thr;
std::atomic<bool> done;
};
That's off the top of my head; not compiled, not tested.

Related

Calling detach() at the end of the thread

I have a working thread similar to the following code. In begin_work, it will check whether the working thread is executing before creating a new working thread. However, begin_work will never create the next working thread when the current thread is exited until I call end_work.
I have tried to call detach at the end of the thread and it works fine. Is it safe to call detach at the end of the thread? Or, how can I do to safely create the next working thread without calling end_work before calling begin_work?
class thread_worker {
private:
std::thread worker;
// ... other menbers
public:
thread_worker() {};
~thread_worker() { end_work(); };
void begin_work() {
if (!worker.joinable()) {
worker = std::thread { &thread_worker::do_work, this };
}
}
void do_work() {
// ... access other members ...
if (exit not by notify) {
worker.detach(); // can I call detach?
}
}
void end_work() {
if (worker.joinable()) {
// notify worker to exit
worker.join();
}
}
};
Edit:
My purpose is to call begin_work without block. If there is one working thread on execution, then the function will return directly or returns an is_working error. Otherwise, create a new working thread seamlessly.
Since std::thread::joinable() always returns true until join or detach is called. As a result, the future call of begin_work will never create the new working thread even though the current working thread has exited.
Therefore, I need a mechanism to automatically detach at the end of the thread.
I have tried to call detach at the end of the thread and it works fine
There's data race in the access to worker - it's undefined behaviour. When begin_work tests worker.joinable(), do_work might be detaching it at the same time (the call to worker.detach()).
You can instead detach the immediately when creating it:
worker = std::thread { &thread_worker::do_work, this };
worker.detach();
However, this can leave multiple threads running at the same time, which contradicts your requirement of running one worker thread at a time (but why only one? that just makes threading pointless).
Instead you can do:
void begin_work() {
end_work();
worker = std::thread { &thread_worker::do_work, this };
}
which ensures the previous thread completed.
Based on yuor edit, you only need to check whether you can join without wait - that seems to be reason you want to detach. You can instead do that with an atomic flag. Basically, you just to take care of the data race noted above.
class thread_worker {
private:
std::thread worker;
std::atomic_bool w_done {true};
// ... other menbers
public:
thread_worker() {};
~thread_worker() { end_work(); };
void begin_work() {
if (w_done) {
end_work();
worker = std::thread { &thread_worker::do_work, this };
}
}
void do_work() {
// ... access other members ...
w_done = true;
}
void end_work() {
w_done = false;
if (worker.joinable()) {
// notify worker to exit
worker.join();
}
}
};

Get std::thread's thread:id before it runs?

I'm trying to build a thread-safety layer on top of C++ 11's std::thread where each object is assigned to an owning thread, and certain calls can raise a hard error when they are used on the wrong thread. The owning thread is the only one that can transfer an object to another thread.
I have it all working, except that I can't find a way to get a thread's thread::id before it is actually running. And I need to attach the new thread's ID to the object before I hand it off.
If I use
std::thread newThread( [theObject]()
{
// use theObject here.
} );
The earliest point I can get the thread's ID is after the definition of the thread object, at which point the thread is already running.
I see there is a default constructor for std::thread, but I can't see a way to give it a function to run on the thread afterwards.
Is there a way to perform two-step construction on a thread, or control the thread's ID at time of creation?
Rather than getting the ID of the thread before it starts running, you could consider having the function the thread executes do some initial setup before taking off. For example, you could do something like this:
bool isReady = false;
bool wasReceived = false;
std::mutex mutex;
std::condition_variable condition;
std::thread newThread([theObject, &isReady, &mutex, &condition] {
/* Wait until we've been cleared to go. */
std::unique_lock<std::mutex> lock(isReady);
condition.wait(lock, [&isReady] { return isReady; });
/* Signal that we're done. */
wasReceived = true;
lock.unlock();
condition.notify_one();
/* Put code here to do whatever it is that the thread should do. */
});
/* Read the thread's ID. It's currently waiting for us. */
auto id = newThread.get_id();
/* Tell the thread that we're ready for it. */
std::unique_lock<std::mutex> lock(mutex);
isReady = true;
condition.notify_one();
/* Wait until the thread has confirmed that it's ready. */
condition.wait(lock, [&] { return wasReceived; });
This creates the thread and has it sit and wait until the creator has a chance to read its ID. Once that's happened, the creator then waits until the thread confirms that it's ready to go, and from there you can work with the thread ID however you'd like.
Beware of bugs in the above code - it's completely untested. :-)
No--as soon as you create a thread, it starts to run. If you want to get its ID before it does (much of) anything, you probably want to create a little wrapper, where you pass the thread (for example) a CV and a queue where it deposits its output.
Then when the thread starts up, it retrieves its own ID, deposits it in the output queue, and then waits on the CV. When the parent has retrieved the ID, and is ready for the child to start doing something, it signals the CV, and off it goes.
Start each thread inactived by passing a unique std::promise parameter, get the thread id first ( thread id is used as a pass by reference parameter for the purpose) afterwards let it wait for the promise to be set by the thread manager. This will also remove the hassle of using a conditional variable.
Edited Snippet
class smart_thread {
public:
smart_thread(std::function<void(void)> task)
{
thread_ = std::thread([=]() {
id_ = std::this_thread::get_id();
// wait here till activated
future_.get();
if(active_) task();
});
}
void activate() {
promise_.set_value();
active_ = true;
}
~smart_thread() {
if(!active_) promise_.set_value();
thread_.join();
}
private:
std::thread::id id_;
std::atomic<bool> active_ = false;
std::thread thread_;
std::promise<void> promise_;
std::future<void> future_ = promise_.get_future();
};
void main()
{
auto task = []() { std::cout << "Hello World\n"; };
smart_thread thread(task); // start thread inactive mode
thread.activate(); // activate thread
}
Would it be possible to create a template class that accepts the thread routine in the form of a std::function<void(T *object)>. This can easily be done with an anonymous closure if additional parameters need to be passed in.
template <class T>
class ThreadWrapper
{
public:
ThreadWrapper(std::function<void(T *object)> function, T *object) :
{
m_thread = std::thread(WrapFunction, function, object);
//optionally
m_thread.detach();
}
static void WrapFunction(ThreadWrapper *wrapper, std::function<void()> function, T *object)
{
// Get the thread id and save in the object
object->SetThreadId(get_id());
// Now actually invoke the thread routine, with the id already installed.
function(object);
}
}
// Cleanup is left as an exercise for the reader.
Beware of bugs in the above code - it's completely untested. :-) :-)

Deleting boost::thread descendant

I am trying to write a class that would run a thread upon its object creation and stop the thread once the object gets deleted.
class MyThread : public boost::thread {
public:
MyThread() : bAlive(true) {
boost::thread(&MyThread::ThreadFunction,this);
}
~MyThread() {
{
boost::unique_lock<boost::mutex> lock(Mutex);
bAlive=false;
}
ConditionVariable.notify_one();
join();
}
private:
volatile bool bAlive;
boost::mutex Mutex;
boost::condition_variable ConditionVariable;
void ThreadFunction() {
boost::unique_lock<boost::mutex> lock(Mutex);
while(bAlive) {
ConditionVariable.timed_wait(lock,boost::get_system_time()+ boost::posix_time::milliseconds(MAX_IDLE));
/*******************************************
* Here goes some code executed by a thread *
*******************************************/
}
}
};
Theoretically, I want to wake the thread up instantly as soon as it needs to be finished, so I had to use timed_wait instead of Sleep.
This works fine until I try to delete an object of this class. In most cases, it deletes normally, but occasionally it causes an error either in condition_variable.hpp, thread_primitives.hpp or crtexe.c. Sometimes I am notified that "Free Heap block 3da7a8 modified at 3da804 after it was freed", and sometimes I'm not. And yes, I'm aware of the spurious wakeups of timed_wait, in this case it's not critical.
Can you please point me to the source of my problem? What am I doing wrong?
I see what you're trying to do but it doesn't work as you expect:
MyThread foo;
default constructs a boost::thread (because MyThread is derived from boost::thread).
The default constructor creates a boost::thread instance that refers to Not-a-Thread.
MyThread() {
boost::thread(&MyThread::ThreadFunction,this);
}
is actually creating a different thread and you're ignoring the returned object (the valid thread).
~MyThread() {
// ...
join();
}
is then trying to join the default constructed thread (which throws an exception inside the destructor) and you never join the thread that actually does the work.
First of all, don't derive from boost::thread. Create a member variable instead:
class MyThread {
// ...
private:
// ...
boost::thread _thread;
};
In the constructor, create and assign a thread to that member variable:
MyThread() {
_thread = boost::thread(&MyThread::ThreadFunction,this);
}
and call its join() in your destructor.
~MyThread() {
// ...
_thread.join();
}
That should fix your problem.
However, if you simply want to exit the thread when your object is destroyed (and don't have to wake it up while its running), you can use a different approach. Remove the mutex and the condition variable and use interrupt instead. This will cause sleep() to throw an exception so you have to catch it:
void ThreadFunction() {
try {
for(;;) {
boost::this_thread::sleep(boost::posix_time::milliseconds(MAX_IDLE));
// Here goes some code executed by a thread
}
} catch( const boost::thread_interrupted& e ) {
// ignore exception: thread interrupted, exit function
}
}
This will instantly exit the ThreadFunction when the thread is interrupted. If you don't need the thread to sleep every cycle, you can replace it with boost::this_thread::interruption_point(). This will just throw an exception if the thread is interrupted.
Now you can simply interrupt the thread in the destructor:
MyThread::~MyThread() {
_thread.interrupt();
_thread.join();
}

wxWidgets wxThread Delete for a Joinable Thread

I got a question about joinable threads in wxWidgets.
When the user wants it, I want to stop a thread doing some work. For that reason I call in this worker thread TestDestroy() to check whether the thread should be stopped. But I can only stop the thread this way by calling Delete(), which should not be called for joinable threads.
Is there a possibility for me to stop the thread (using TestDestroy) or do I have to change my code completely?
Thanks in advance,
TiBo
The current documentation for wxThread::Delete() says:
This function works on a joinable thread but in that case makes the TestDestroy() function of the thread return true and then waits for its completion (i.e. it differs from Wait() because it asks the thread to terminate before waiting).
So, it appears that you can use Delete() on a joinable thread.
You have to call the Exit() method from your worker thread or simply return from the Run method AND call the MyThread->Wait() method then delete the thread object.
Declaring the thread :
class MyThread : public wxThread {
virtual void * run();
};
Thread implementation :
MyThread::run()
{
while(1)
{
if(TestDestroy())
{
this.Exit(); // or return;
}
// Do some work
}
}
Declaring the Thread pointer :
MyThread * pMyThread;
Creating, launching and stopping the thread
void launchThread{
pMyThread = new wxThread(wxTHREAD_JOINABLE);
pMyThread->Create();
pMyThread->Run();
}
void stopThread(){
pMyThread->Delete();
pMyThread->Wait();
delete pMyThread;
}
Hope that it helps.
P.S. : this is my first answer on Stack Overflow. I don't know how I can easilly write some code automatically indented?
You shouldn't have to rewrite your code.
It's usually best that a thread terminates by returning from it's main function, as the documentation suggests.
One way of achieving this, and probably the easiest, is to throw some object that will be caught in the main thread function.
For example:
struct ThreadEndingException { };
void DoSomeWork() {
...
if (TestDestroy())
throw ThreadEndingException();
...
}
void ThreadFunction() {
try {
DoSomeWork();
}
catch (const ThreadEndingException&) {
// Do nothing, the function will return after leaving this catch.
}
}

Implement a multithreading environment

I want to implement a multithreading environment using Qt4. The idea is as follows in c++-alike pseudo-code:
class Thread : public QThread {
QList<SubThread*> threads_;
public:
void run() {
foreach(SubThread* thread : threads) {
thread.start();
}
foreach(SubThread* thread : threads) {
thread.wait();
}
}
void abort() {
foreach(SubThread* thread : threads) {
thread.cancel();
}
}
public slots:
// This method is called from the main-thread
// (sometimes via some signal-slot-connection)
void changeSomeSettings() {
abort();
// change settings
start();
}
}
class SubThread : public QThread {
bool isCancelled_;
public:
void run() {
while(!isCancelled or task completed) {
// something that takes some time...
}
}
void cancel() {
if(isRunning() {
isCancelled_ = true;
}
}
}
The purpose is that the slot changeSomeSettings() kills all running threads, commits its changes and restarts it. What I want to achieve is that once this method has been started, it calls "abort" and then waits until all threads have terminated. Using mutexes in a wrong way:
void Thread::changeSomeSettings() {
mutex1.lock();
abort();
mutex2.lock();
start();
mutex1.unlock();
}
void Thread::run() {
foreach(Thread* thread : threads) {
thread.start();
}
foreach(Thread* thread : threads) {
thread.wait();
}
mutex2.unlock();
}
This actually works in Qt under MacOSX, yet according to the documentation mutex2 must be unlocked in the same thread (and in Windows I get an error). What is the best way to achieve my goal without running into racing conditions and deadlocks? Is there a better design than the one I have proposed here?
You probably want to use a condition variable instead of a mutex for this situation. A condition variable is a way for one thread to signal another. QT's implementation appears to be the QTWaitCondition:
I might have the child thread's periodically check the state of the condition variable. This can be done with QTWaitCondition::wait() with a short/0 timeout. If it is being signaled, then lock a shared memory area containing updated data and access the data that needs to be updated. Then that thread can safely restart itself accordingly.
It's usually not a good idea to just abort a thread. You may end up leaking memory/resources/handles/locks/etc. You don't know where that thread is in it's call stack, and there may be no guarantees that the stack will be "unwound" for you and all destructors are called. This is another reason for the child threads checking a condition variable periodically for updated data and having them restart themselves safely with the new data.