/Pthreads – II

Pthreads – II


The previous part introduced the basic usage of Pthreads , If you didn”t read it please refer to this link before you continue reading this topic…

Now what are threads without synchronization 😉 , the threads library offers 3 synchronization techniques : Mutexes , joins and conditional variables , this topic will handle mutexes , the rest will be in another topic.

Mutexes are used to prevent data inconsistencies that can happen due to operations of multiple threads on the same memory area , It can be also used to prevent race conditions , where and order of an operation is expected..meaning that the result of an operation depends on the order of the threads , and to protect what we call “critical memory” from other casino online threads, anytime a global resource is accessed by more than one thread the resource should have a Mutex associated with it.

Note that mutexes are only applied to threads in a single process not to different processes .

Now let”s hop on to the code

The code is pretty much straight forward but it shows how you must always be extra careful when using global variables , you want to add 1 to counter then multiply it by 5

compile and run
-$ gcc -o mutex1 mutex1.c -lpthread

you should get
Counter value: 1
Counter value: 5

now if you comment out the mutexes and recompile try running it couple of times and you”ll notice the error
$ ./mutex1
Counter value: 0
Counter value: 1

** as you see thread2 operated before thread1 yielding a wrong result.