# How to trigger a thread to start working using semaphore?

How to trigger a thread to start working using semaphore?

I have find a lot of explanation about thread and semaphore but i still don't understand, any help please

• Do you think this is Computer Science? – gnasher729 Jun 6 at 10:29
• According to Wikipedia, in computer science, a semaphore is a variable or abstract data type used to control access to a common resource by multiple processes in a concurrent system such as a multitasking operating system. – Pål GD Jun 6 at 11:29
• It's not true that everything related to programming is outside the realm of computer science. – Pål GD Jun 6 at 11:30

When using semaphores or locks, you don't do anything else than acquiring the semaphore (resp. the lock), and then do what you want. For example, if you want to use a lock, then you typically have two threads

# thread 1
lock.acquire()
# here is all the work for thread 1
lock.release()


and the other thread is completely identical:

# thread 2
lock.acquire()
# here is all the work for thread 2
lock.release()


Now, the first to obtain the lock gets to run the code first, and the other thread needs to wait until the lock is released.

Here's an example of a Python program that prints a series of 0s and 1s depending on the order of execution:

import time

lst = []

def f1():
for i in range(10):
lock.acquire()
lst.append("0")
lock.release()
time.sleep(0.1)

def f2():
for i in range(10):
lock.acquire()
lst.append("1")
lock.release()
time.sleep(0.1)


(Note that I used lock.acquire() and lock.release(), but the "correct" way is to use a context manager and use with lock: ....)