请写一个多线程python程序要求生成16个线程运行函数getData直到有一个函数返回结果然后输出返回值并删除其它线程
以下是一个符合要求的多线程Python程序:
import threading
# 定义一个全局变量,用于存储返回结果
result = None
# 定义一个锁,用于保护全局变量的访问
lock = threading.Lock()
# 定义一个函数,模拟获取数据的操作
def getData():
global result
# 模拟获取数据的过程
# 这里可以根据实际情况进行修改
import time
import random
time.sleep(random.randint(1, 5))
# 生成随机的返回结果
with lock:
if result is None:
result = random.randint(1, 100)
# 定义一个线程类
class MyThread(threading.Thread):
def run(self):
getData()
# 创建16个线程并启动
threads = []
for _ in range(16):
thread = MyThread()
threads.append(thread)
thread.start()
# 等待所有线程完成并输出结果
for thread in threads:
thread.join()
# 输出结果并删除其它线程
with lock:
print("返回结果:", result)
for thread in threads:
if thread.is_alive():
thread.join()
print("删除线程:", thread)
这个程序会生成16个线程,并且每个线程都会调用函数getData来获取数据。当有一个线程返回结果后,程序会输出返回值,并删除其它线程。在输出结果和删除线程的过程中,使用了一个锁来保护全局变量的访问,以避免多个线程同时访问导致的竞争条件。
原文地址: https://www.cveoy.top/t/topic/jfEA 著作权归作者所有。请勿转载和采集!