Grokking Multithreading and Concurrency for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
3. Semaphore
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

In this example, we focus on a shared variable named counter, which is accessed by several threads at the same time. We create 10 threads for this task. Each thread works to increase the counter value, but only 5 threads are allowed to do this at the same time. This limit of 5 is set by a semaphore. The goal is for the counter to reach a specific number, called TARGET_VALUE, which is 5000 in our case.

Here are the main points of this setup:

  • We use a semaphore to control how many threads can increase the counter at one time. In our program, up to 5 threads can do this simultaneously.
  • If more than 5 threads try to increase the counter, the extra threads have to wait. This is how the semaphore keeps things orderly.
  • Using a semaphore allows several threads to work together but prevents too many from doing the same thing at once.

This demonstration shows us how useful a semaphore is in situations where you want to let multiple threads do the same task at the same time, but you also want to keep control and avoid chaos. By using a semaphore, our program lets several threads increase the counter quickly while making sure there is an upper limit on concurrency.

Python3
Python3

. . . .

Experiment Idea: Experiment with adjusting the semaphore count from its current setting of 5. Observe and analyze how changes in this count affect the overall time taken to complete the program's execution. Does increasing or decreasing the count make the program run faster or slower? What's the impact on performance and why?

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible