为什么先输出100个1再输出100个2
import threading
lock = threading.Lock()
shared_value = 0
def thread1_func():
global shared_value
lock.acquire() # 获取锁
for _ in range(100):
print(1)
shared_value += 1
lock.release() # 释放锁
def thread2_func():
global shared_value
lock.acquire() # 获取锁
for _ in range(100):
print(2)
shared_value -= 1
lock.release() # 释放锁
thread1 = threading.Thread(target=thread1_func)
thread2 = threading.Thread(target=thread2_func)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("Shared Value:", shared_value)
你加了lock.acquire(),thread1_func获取到锁后,执行完循环才释放锁。thread2_func在thread1_func执行过程中,因为获取不到锁,所以一直处于pending状态。你把lock.acquire()和lock.release()去掉,或者改成这样:
def thread1_func():
global shared_value
for _ in range(100):
lock.acquire() # 获取锁
print(1)
shared_value += 1
lock.release() # 释放锁
def thread2_func():
global shared_value
for _ in range(100):
lock.acquire() # 获取锁
print(2)
shared_value -= 1
lock.release() # 释放锁
lock锁机制,一个线程获取了锁之后,其他线程就不能再获取锁,只能等待锁被释放,所以代码的输出结果是先输出 100 个 1,再输出 100 个 2
要是想同时输出,试试Queue队列 ,Queue提供了一个线程安全的队列,可以在多个线程之间安全地传递数据,代码已测试
import threading
import queue
# 创建两个队列
q1 = queue.Queue()
q2 = queue.Queue()
# 往队列中添加数据
for _ in range(100):
q1.put(1)
q2.put(2)
# 定义第一个线程的执行函数
def thread1_func():
for _ in range(100):
print(q1.get())
# 定义第二个线程的执行函数
def thread2_func():
for _ in range(100):
print(q2.get())
# 创建两个线程
thread1 = threading.Thread(target=thread1_func)
thread2 = threading.Thread(target=thread2_func)
# 启动两个线程
thread1.start()
thread2.start()
# 等待两个线程执行完毕
thread1.join()
thread2.join()