from threading import Thread, Lock, Barrier, current_thread from multiprocessing import Process, Pipe, current_process from queue import Queue from time import sleep # Manual synchronization using a lock counter = [0] counter_lock = Lock() def increment3(): counter_lock.acquire() count = counter[0] sleep(0) # try to force a switch to the other thread counter[0] = count + 1 counter_lock.release() def lock_increment(): other = Thread(target=increment3, args=()) other.start() increment3() other.join() print('count is now:', counter[0]) # lock_increment() # The with statement def increment3(): with counter_lock: count = counter[0] sleep(0) # try to force a switch to the other thread counter[0] = count + 1 # lock_increment() # Using a barrier counter = [0] barrier = Barrier(2) def increment4(my_phase, num_phases): for i in range(num_phases): if i == my_phase: count = counter[0] sleep(0) # try to force a switch to the other thread counter[0] = count + 1 barrier.wait() def barrier_increment(): other = Thread(target=increment4, args=(1, 2)) other.start() increment4(0, 2) print('count is now: ', counter[0]) # barrier_increment() # Using message passing counter = [0] def increment5(my_pipe): count = my_pipe.recv() # no need to sleep; processes run concurrently! counter[0] = count + 1 # keep a copy of my last computed value my_pipe.send(counter[0]) def message_increment(): pipe = Pipe() other = Process(target=increment5, args=(pipe[1],)) other.start() pipe[0].send(0) increment5(pipe[0]) other.join() print('count is now:', counter[0]) # message_increment()