When to use event/condition/lock/semaphore in python's threading module?
Asked Answered
P

1

9

Python provides 4 different synchronizing mechanisms in threading module: Event/Condition/Lock(RLock)/Semaphore.

I understand they can be used to synchronize access of shared resources/critical sections between threads. But I am not quite sure when to use which.

Can they be used interchangeably? Or are some of them 'higher level', using others as building blocks? If so, which ones are built on which?

It would be great if someone can illustrate with some examples.

Penetralia answered 27/7, 2015 at 3:47 Comment(1)
I think this question is a little too broad, but to answer part of it: Condition is built on top of Lock, and Event and Semaphore are built on top of Condition.Ruthanneruthe
B
10

This article probably contains all the information you need. The question is indeed very broad, but let me try to explain how I use each as an example:

  1. Event - Use it when you need threads to communicate a certain state was met so they can both work together in sync. I use it mostly for initiation process of two threads where one dependes on the other.

    Example: A client has a threaded manager, and its __init__() needs to know the manager is done instantiating some attributes before it can move on.

  2. Lock/RLock - Use it when you are working with a shared resource and you want to make sure no other thread is reading/writing to it. Although I'd argue that while locking before writing is mandatory, locking before reading could be optional. But it is good to make sure that while you are reading/writing, no other thread is modifying it at the same time. RLock has the ability to be acquired multiple times by its owner, and release() must be called the same amount of times acquire() was in order for it to be used by another thread trying to acquire it.

I haven't used Condition that much, and frankly never had to use Semaphore, so this answer has room of editing and improvement.

Biotin answered 28/8, 2015 at 20:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.