Skip to content

Concurrency

Jasper Zanjani edited this page Sep 14, 2020 · 1 revision

👉 Understanding async and await in Python

Concurrency can be implemented in several ways:

Because of the way the bytecode treats the global variable, this example results in counter drifting increasingly further from zero, despite impressions.

counter = 0

def func1():
  global counter

  while True:
    counter += 1
    counter -= 1

def func2():
  global counter

  while True:
    counter += 1
    counter -= 1

threading.Thrad(target=func1).start()
threading.Thrad(target=func2).start()

The solution is to use threading.RLock, which prevents the two threads from manipulating the same variable at the same time.

counter = 0
lock = threading.RLock()

def func1():
  global counter

  while True:
    with lock:
      counter += 1
      counter -= 1

def func2():
  global counter

  while True:
    with lock:
      counter += 1
      counter -= 1

threading.Thrad(target=func1).start()
threading.Thrad(target=func2).start()

But locks have overhead and bring the risk of deadlocking. Synchronization is required when accessing shared data structures.

Instead of udsing locks, people often use queues (message passing) for inter-thread communication.

Threads vs coroutines

Threads Coroutines
Preemptive Cooperative
OS decides Tasks decide
Context switching prevented using locks Context switching allowed upon await

Clone this wiki locally