What is Thread Synchronization?
In a multithreaded environment, each thread has its own local thread stack and registers. If multiple threads access the same resource for read and write, the value may not be the correct value. For example, let's say our application contains two threads, one thread for reading content from the file and another thread writing the content to the file. If the write thread tries to write and the read thread tries to read the same data, the data might become corrupted. In this situation, we want to lock the file access. The thread synchronization has two stages. Signaled and non-signaled.
The signaled state allows objects to access and modify data. The non-signaled state does allow accessing or modifying the data in the thread local stack.
Thread Synchronization methods:
Many of the thread synchronization methods are used to synchronize multiple threads. The following methods are used to synchronize between objects.
Thread Synchronization on different processes:
Event:
Event is a thread synchronization object used to set the signaled or non-signaled state. The signaled state may be manual or automatic depending on the event declaration.
Mutex:
Mutex is the thread synchronization object which allows to access the resource only one thread at a time. Only when a process goes to the signaled state are the other resources allowed to access.
Example:
Mutex is a key to a meeting room. One person can have the key - occupy the meeting room - at the time. When finished, the person gives (frees) the key to the next person in the queue.
(A mutex is really a semaphore with value 1.)
Semaphore:
Semaphore is a thread synchronization object that allows zero to any number of threads access simultaneously.
Example:
Semaphore is the number of free identical keys. Example, say we have four meeting room with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four meeting rooms are free), then the count value is decremented as people are coming in. If all meeting rooms are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the meeting room, semaphore is increased to 1 (one free key), and given to the next person in the queue.
Thread Synchronization in same process:
Critical Section
The critical section is a thread synchronization object. The other synchronization objects like semaphore, event, and mutex are used to synchronize the resource with different processes. But, the critical section allows synchronization within the same process.
No comments:
Post a Comment