Running two or more threads independently, where each accesses its own resources, is quite convenient. However, sometimes, we want the threads to share and process the same resource simultaneously so that we can finish a task faster. Sharing a common resource may lead to problems, as one thread might read the data before the other thread writes the updated data, leading to an ambiguous situation. To avoid such a situation, mutex is used. In this recipe, you will learn how to share common resources between two threads.
Using mutex to share data between two threads
How to do it…
- Define two variables of the pthread_t type to store two thread identifiers. Also, define a mutex object:
pthread_t tid1,tid2;
pthread_mutex_t...