import threading
import time
import random
# 共享数据的字典
shared_data = {}
def worker1(d):
# 在字典中设置数据
while True:
st = time.time()
num = random.randint(0, 100)
print("num=========",num)
d['key'] = 'value from worker_'+str(num)
#print('Worker 1 sets data.')
fps = 25
tmspan = 1 / fps
et = time.time()
respan = et - st
sleeptime = tmspan - respan
if sleeptime < 0:
sleeptime = 0
print("sleeptime=====",sleeptime)
time.sleep(sleeptime)
def worker2(d):
# 等待worker1设置数据
# while 'key' not in d:
# time.sleep(0.1)
while True:
camID = 'key'
for camID in d:
print("=====",d[camID])
# 获取并打印数据
print(f'Worker 2 gets data: {d["key"]}')
# 创建线程
t1 = threading.Thread(target=worker1, args=(shared_data,))
t2 = threading.Thread(target=worker2, args=(shared_data,))
# 启动线程
t1.start()
t2.start()
# 等待线程完成
t1.join()
t2.join()
利用线程实现共享字典来进行数据通信
最新推荐文章于 2024-08-29 10:04:09 发布