Semaphore Mutex Concurrency Problem in a multithreaded C program
There are several ways.
The best way is to remove all shared data between threads. While this is not always practical, it is always a good idea to eliminate as much common data as possible.
After that, you need to start looking for light-hearted programming. Locking programming is a bit fancy nowadays, but the dirty secret is that it is often much better to use ww90 locks, such as mutexes and semaphores. The blocking program is very difficult to get right. Check out Herb Sutter's articles on this topic or the Wikipedia page. There are many good resources out there on worry-free syncing.
Somewhere in between are critical sections. If you are programming on Windows, critical sections should be preferred over mutexes as they do some work to avoid the overhead of locking and unlocking all mutexes. Try them first, and if your performance is unacceptable (or you're targeting platforms without critical sections), you can look at light-hearted methods.
a source to share
Be sure to pass data structures between threads, always knowing which stream only the data belongs to. If you use (as Dan mentioned earlier) eq blocked queues to transfer your data, you shouldn't run too many concurrency problems (since your code behaves a lot more like any other code waiting for some data to arrive).
If you are porting single- and multi-threaded code nonetheless, this is a completely different beast. It is very difficult. And most of the time, there are no elegant solutions.
a source to share