What to avoid when coding for multithreading?

Jul 7, 2009 at 7:31am
I would like to ask some experienced multithreading C++ developers, what types of constructs and design patterns we should avoid if we eventually want to convert a library into a threadsafe/reentrant lib.

Eventually, I would like my library to work with boost threads.

For example, I hear the following are bad:
1. Global vars: static in a .cpp, static in a function, static in a class
2. Singletons and Multitons (is this right?)

Please add any others that you think I should avoid.
Thanks.

- Ken
Jul 7, 2009 at 9:50am
The rule is "don't access unatomic or unsafe shared resources without locking them with a mutex/semaphore". For example of said resources: rand(), std::cout, anything from the STL with shared access (such as a pointer to an std::vector passed to all threads).
Last edited on Jul 7, 2009 at 9:51am
Jul 7, 2009 at 10:42am
helios, thanks for your comment.

In your experience, is it better to lock shared resources regardless of read/write access or is it worth the effort to lock for write only?

Also, is there any way to tell which classes or resources are safe and which are not? Can you only tell from documentation or is there some framework that you can use to test for safety?
Jul 7, 2009 at 11:42am
Your instinct should be lock things, but there are variances.

For example, a cache may support multiple parallel readers with a writer requiring an exclusive lock. Excessive locks can slow you unnecessarily.
Jul 7, 2009 at 1:28pm
Thanks for your suggestion, kbw.

Are there any open-source tools out there that you like for unit-testing multi-threaded code?

I suspect it would almost have to act like a mock-class to replace some threading interface (like boost) to produce a deterministic result...

I recently saw something called Valgrind/Helgrind:

http://valgrind.org/

which looks like it might work. Any ideas?
Jul 7, 2009 at 3:04pm
I understood Valgrind was a heap checking tool and not specifically a mult-thread checking tool, but I could be wrong.

Another thing to look out for is dead-locks. If you have one thread the sends a message to another thread and waits for a reply, but the two threads share some library or class that has locks, you can dead-lock in interesting ways.

I'm not sure if you'll find a mult-threading test harness as identifying the different ways you can encounter problems is so varied.
Jul 7, 2009 at 9:23pm
Helgrind does detect race conditions in multithreaded code.
Topic archived. No new replies allowed.