Skip to content

Semaphore program: Demonstrates semaphore usage to restrict threads in a critical code section, allowing up to a specific amount of concurrent threads. Mutex program: Illustrates mutex usage for thread synchronization, ensuring only one thread enters the critical region at a time.

Notifications You must be signed in to change notification settings

TryingToBeSmart/Semaphore-and-Mutex

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Semaphore and Mutex

Semaphore program

This simple semaphore program shows how to restrict threads from entering into a critical area of code by using semaphores to limit the amount of threads that can in the critical area at one time. I restrict them to 10 by with this code: semaphore = sem_open("Semaphore", O_CREAT, 00644, 10); 10 as the last argument means that this semaphore will allow up to 10 concurrent threads into the critical section. Then, when the threads are created using a for loop and pthread_create, they all begin running the connect() function. The connect() function contains the critical region. sem_wait allows a thread in and then decrements the number of available openings that are left. When there are 10 threads in the critical region, then it stops letting threads in. When a thread is finished in the critical region, they call the sem_post function which adds 1 to the available opening and then the semaphore lets a new thread in.

Video:

Semaphore video

Mutex program

This mutex program shows how to restrict threads from entering a critical region of code by using a mutex. This only allows 1 thread to enter the critical region at a time because only the thread that has possession of the mutex can be in the critical region. pthread_mutex_init is used to initialize the mutex, pthread_mutex_lock is used to allow 1 thread in and then lock the region, and pthread_mutex_unlock is used when the thread is finished and then the next thread can get the mutex and enter the critical region.

Video:

Mutex video

About

Semaphore program: Demonstrates semaphore usage to restrict threads in a critical code section, allowing up to a specific amount of concurrent threads. Mutex program: Illustrates mutex usage for thread synchronization, ensuring only one thread enters the critical region at a time.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages