Search

Using pthread_mutex to lock and synchronize threads

pthreads are used to split a process into multiple threads and execute them concurrently. The threads should be independent of each other as far as possible, but at times the threads could be dependent on each other and they might be working on the same data.

Let us say we want to crate two threads,one to read from a file and the other to write into the same file. It is obvious that we can not read from a file unless we don't write into it, and at any given time the file should be allowed to be accessed by only one of the two threads. That is while it is being written it should not be allowed to be read and while it is being read, it should not be opened for write.

The following program implements the above mentioned two threads, but does not do any thing to synchronize the actions of the two threads.



Save the adove file as pthread_file.c. Compile it using "-lpthread" falg



We get a segmentation fault every time we execute the above program. This is because, the read thread tries to access the file which is being created by thread1 "write" and thus is still not available. When read thread accesses the file it still has not been created and thus we get a segmentation fault.

The part of the program in which multiple threads try to get access to the same resource, in this case the file, is termed as the critical section and ideally a critical section should be executed by only one thread at a any given time.

To prevent the access of the file by multiple threads at the same time we can make use of a mutex. Mutex stands for mutual exclution and as the name implies it keeps the threads mutually exclusive.

Access to the critical section is controlled by locking the mutex. That is whichever process locks the mutex first will be allowed to enter the critical section first and the other process can not enter the critical section unless the mutex is not unlocked by the first process.

Applying this to above example, both read and write threads will have to get a lock on a common mutex before getting access to the file. If we can make sure that the write thread always gets the access to the lock first then, the read thread will have to wait for the write thread to finish its operations on the file and unlock the mutex,before it can read it. Thus making sure that the segmentation fault never ocurrs.

To implement a mutex in pthreads we have to use a datatype of type pthread_mutex_t.
e.g.



To lock the mutex we use the function pthread_mutex_lock(Address of mutex variable)
e.g.



To unlock the mutex we use the functions pthread_mutex_unlock(address of mutex variable)
e.g.


The implementation is shown in the code below.

pthread_mutex.c



save the code as pthread_mutex.c and compile by passing the "-lpthread" flag and execute it.




Follow by Email