The case of the crashing std::thread destructor and why you should use tasks instead of threads

 

You are reading the old blog! This post has been moved to http://www.ohadsoft.com/2015/01/the-case-of-the-crashing-stdthread-destructor-and-why-you-should-use-tasks-instead-of-threads/

 

I recently encountered an interesting crash in our iOS application at work. Here’s the relevant stack trace section:

…
libc++abi.dylib <strong>std::terminate</strong>()
libc++.1.dylib  <strong>std::__1::thread::~thread</strong>()
…

Luckily, the documentation for std::~thread provides us with the root cause:
If *this has an associated thread (joinable() == true), std::terminate() is called.

Specifically, the joinable() documentation states:
A thread that has finished executing code, but has not yet been joined is still considered an active thread of execution and is therefore joinable.

Seeing as the thread in question was indeed never joined (or detached) we were hit by this error. Now, this issue can be solved by joining with or detaching from the thread, but I think that would be the wrong lesson to learn here.

This is just one example of how things are more difficult with threads than they are with tasks. Practically any imaginable scenario is made easier and less error-prone with tasks. Just as tasks were a paradigm shift in .NET, they should be in C++11 – only manipulate threads directly if you must!

Advertisements

One Response to “The case of the crashing std::thread destructor and why you should use tasks instead of threads”

  1. idogal Says:

    Great post. Thanks.

    Liked by 1 person

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: