Skip to content

Instantly share code, notes, and snippets.

@laixintao
Created April 8, 2019 11:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save laixintao/cc490c3f840a0003f27c67e6f2af2694 to your computer and use it in GitHub Desktop.
Save laixintao/cc490c3f840a0003f27c67e6f2af2694 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
"""
Three threads print A B C in order.
"""
from threading import Thread, Condition
condition = Condition()
current = "A"
class ThreadA(Thread):
def run(self):
global current
for _ in range(10):
with condition:
while current != "A":
condition.wait()
print("A")
current = "B"
condition.notify_all()
class ThreadB(Thread):
def run(self):
global current
for _ in range(10):
with condition:
while current != "B":
condition.wait()
print("B")
current = "C"
condition.notify_all()
class ThreadC(Thread):
def run(self):
global current
for _ in range(10):
with condition:
while current != "C":
condition.wait()
print("C")
current = "A"
condition.notify_all()
a = ThreadA()
b = ThreadB()
c = ThreadC()
a.start()
b.start()
c.start()
a.join()
b.join()
c.join()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment