本文共 1792 字,大约阅读时间需要 5 分钟。
在Python中,多线程编程可以通过threading模块实现。以下是一个简单的多线程并行执行示例:
import threadingimport timedef loop(): print('thread %s is running...' % threading.current_thread().name) n = 0 while n < 5: n += 1 print('thread %s ' % threading.current_thread().name) time.sleep(3) print('thread %s ended.' % threading.current_thread().name)print('thread %s is running...' % threading.current_thread().name)t = threading.Thread(target=loop, name='LoopThread')t.start()# t.join()print('thread %s ended.' % threading.current_thread().name)# 执行结果:# thread MainThread is running...# thread LoopThread is running...thread MainThread ended.# thread LoopThread# thread LoopThread# thread LoopThread# thread LoopThread# thread LoopThread ended. 以下是一个利用队列实现多线程间数据交互的实例:
import Queueimport timeimport threadingimport randomq = Queue.Queue()def pro(name): print("---pro data kaiqi") time.sleep(3) for i in range(20): time.sleep(1) print(name + "pro data" + str(i)) q.put(i)def con(name): print("-----con data kaiqi") n = 0 while n < 20: time.sleep(3) data = q.get() print(name + "con data----" + str(data)) n += 1# 创建并启动子线程t1 = threading.Thread(group=None, target=pro, name=None, kwargs={'name':'laoban'})t2 = threading.Thread(group=None, target=con, name=None, kwargs={'name':'yuangong'})t1.start()t2.start() 在Python中,多线程编程通过threading模块实现,核心原理是抢占式调度。以下是本文中两个示例的主要启示:
j)可以并行执行i)需要串行执行转载地址:http://svlfk.baihongyu.com/