两个线程交替打印数字
小于 1 分钟
题目表述
编写两个线程,一个打印偶数、一个打印奇数;要求按顺序打印。
解答
Python 中线程同步可以通过锁(Lock
)、信号量(Semaphore
)、条件(Condition
)、事件机制(Event
)、队列(Queue
)来实现。
代码实现
# 两个线程,一个打印偶数、一个打印奇数;按顺序打印
import threading
lock1 = threading.Lock()
lock2 = threading.Lock()
lock2.acquire()
def print_odd(upper=100):
"""打印奇数"""
for i in range(1, upper, 2):
lock1.acquire()
print(i)
lock2.release()
def print_even(upper=100):
"""打印偶数"""
for i in range(2, upper, 2):
lock2.acquire()
print(i)
lock1.release()
if __name__ == "__main__":
t1 = threading.Thread(target=print_odd)
t2 = threading.Thread(target=print_even)
t1.start()
t2.start()
t1.join()
t2.join()
# 两个线程,一个打印偶数、一个打印奇数;按顺序打印
import threading
sema1 = threading.Semaphore(1)
sema2 = threading.Semaphore(0)
def print_odd(upper=100):
"""打印奇数"""
for i in range(1, upper, 2):
sema1.acquire()
sema2.release()
print(i)
def print_even(upper=100):
"""打印偶数"""
for i in range(2, upper, 2):
sema2.acquire()
sema1.release()
print(i)
if __name__ == "__main__":
t1 = threading.Thread(target=print_odd)
t2 = threading.Thread(target=print_even)
t1.start()
t2.start()
t1.join()
t2.join()
# 两个线程,一个打印偶数、一个打印奇数;按顺序打印
import threading
condition = threading.Condition()
current = 0
def print_odd(upper=100):
"""打印奇数"""
global current
for i in range(1, upper, 2):
with condition:
if current == 1:
condition.wait()
current = 1
print(i)
condition.notify()
def print_even(upper=100):
"""打印偶数"""
global current
for i in range(2, upper, 2):
with condition:
if current == 0:
condition.wait()
current = 0
print(i)
condition.notify()
if __name__ == "__main__":
t1 = threading.Thread(target=print_odd)
t2 = threading.Thread(target=print_even)
t1.start()
t2.start()
t1.join()
t2.join()
# 两个线程,一个打印偶数、一个打印奇数;按顺序打印
import threading
event1 = threading.Event()
event2 = threading.Event()
event1.set()
def print_odd(upper=100):
"""打印奇数"""
for i in range(1, upper, 2):
event1.wait()
print(i)
event1.clear()
event2.set()
def print_even(upper=100):
"""打印偶数"""
for i in range(2, upper, 2):
event2.wait()
print(i)
event2.clear()
event1.set()
if __name__ == "__main__":
t1 = threading.Thread(target=print_odd)
t2 = threading.Thread(target=print_even)
t1.start()
t2.start()
t1.join()
t2.join()
"""
两个线程,一个打印偶数、一个打印奇数;按顺序打印
队列实现
"""
import threading
from queue import Queue
odd_queue = Queue(1)
even_queue = Queue(1)
def print_odd(upper=100):
"""打印奇数"""
odd_queue.put(1)
while True:
num = odd_queue.get()
print(num)
even_queue.put(num + 1)
if num >= upper:
return
def print_even(upper=100):
"""打印偶数"""
while True:
num = even_queue.get()
print(num)
odd_queue.put(num + 1)
if num >= upper:
return
if __name__ == "__main__":
t1 = threading.Thread(target=print_odd)
t2 = threading.Thread(target=print_even)
t1.start()
t2.start()
t1.join()
t2.join()