CENG460 Operating Systems Spring 2017 -2018 Synchronization (3) Practical exercises in Linux Dr. Omar Chebaro [Operating Systems Concepts, 8th Edition, by Silberschatz, Galvin, and Gagne, 2009] 1 Thread Synchronization O The ultimate cause of most bugs involving threads is that the threads are accessing the same data. That’s one of the powerful aspects of threads, but it can also be dangerous O If one thread is only partway through updating a data structure when another thread accesses the same data structure, problems are likely to arise O These bugs are called race conditions; the threads are racing one another to change the same data structure 2 Example of Race Conditions 3 Solution for Race Conditions O In previous example we saw that the log ‘Job 2 finished’ is repeated twice while no log for ‘Job 1 finished’ is seen O Therefore, threads need to synchronize their access to the shared variable “counter” O Use the system calls for thread synchronization as stated in next slide 4 System Calls for Thread Synchronization We have to include this library: #include <semaphore.h> int sem_init(sem_t *sem, int pshared, unsigned int value); O This function initializes a semaphore object pointed to by sem O value: specifies the initial value of the semaphore O The pshared parameter controls the type of semaphore O If pshared is 0, the semaphore is local to the current process (and its threads) O For now, we are interested only in semaphores from type 0 int sem_wait(sem_t * sem); // function atomically decreases the value of the semaphore by 1 int sem_post(sem_t * sem); // atomically increases the value of the semaphore by one, but always waits until the semaphore has a nonzero count first int sem_destroy(sem_t * sem); O Again, this function takes a pointer to a semaphore and cleans any resources that it may have 5 Example of Synchroniz ed Threads 6