多线程的代码
以下是一个Python的多线程示例代码,它使用了threading模块:
import threading
def worker(num):
"""Thread worker function"""
print('Worker %d started' % num)
return
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
# Wait for all threads to complete
for t in threads:
t.join()
print('All threads finished')
这个示例中,我们定义了一个worker函数,它接受一个参数num,并在启动线程后打印出该参数。我们创建了5个线程,并将它们添加到一个列表中。然后,我们循环遍历线程列表,并使用join函数等待所有线程完成。最后,我们打印出所有线程都已经完成的消息。
值得注意的是,Python中的多线程是基于系统线程实现的,因此具有系统线程的所有特性和限制。因此,在使用多线程时需要注意线程安全和同步问题
原文地址: https://www.cveoy.top/t/topic/eynr 著作权归作者所有。请勿转载和采集!