1

Consider a test case for some Mutex class implementation. The test creates several std::thread instances during execution. All threads should finish if the Mutex class is implemented correctly according to the test. If there is a problem, it's possible that one thread may block indefinitely. How can the test correctly cleanup after itself?

At first I thought to detach the thread, but then the thread is leaked. Even worse, the thread relies on a Mutex instance from inside the test case which will sporadically cause access violations after the test case returns. Some thread libraries such at Qt’s QThread have terminate() methods, but I’d like to use std::thread even though Qt is already a dependency for my project.

Is there a general pattern for testing potentially indefinitely blocking concurrent code?

Dan Watkins
  • 918
  • 9
  • 25

2 Answers2

0

Killing threads that may hold a lock is one of the main reasons terminating threads forcibly is frowned upon, and why C++11 doesn't support it. You are not supposed to do it, period.

If you need to do something like it, your best best would probably be to spawn a new process to run the test in; if it locks up, you can terminate the process without the same risks.

For examples of why terminating threads is bad news, take a look at the specific example from the Old New Thing on what sort of garbage thread termination leaves lying around on Windows; similar issues occur on most operating systems under different contexts.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
-2

I think destructors could come in help here, is the only thing 100% sure that be executed after any problem, by design. I suggest a nice blocking test inside of some destructor and release resources in a SECURE WAY (smart pointers ?) before leave it.

JP Cordova
  • 119
  • 9
  • 1
    How is a destructor wrapping up the test method going to solve the problem? If the std::thread instance's destructor runs inside this wrapper destructor, you still have the problem of destroying a running std::thread which results in your whole application being terminated (crashed). – Dan Watkins Oct 20 '15 at 17:22
  • I wasn't thinking in a thread instance's destructor, could be any destructor with access to the thread handler (thinking in worst case scenario), the solution for this problems are convergent (in 90% of implementations I've seen) using a dedicated process to check problems in threads as ShadowRanger comment before, and can use that destructor for this test in particular, not running a process inside destructor. http://stackoverflow.com/questions/29178435/safely-destroying-a-thread-pool?rq=1 Check this, it is not the same, but will help. – JP Cordova Oct 22 '15 at 15:27