python多线程

学web好迷啊,学下编程先

py3 用的是 threading模块

import threading
import time
简单代码如下:
def fun():#功能
    data = 'time-is:%s'%(time.ctime())
    print(data)

def main():
    threads = [] #存储线程
    threads_count = 10 #设置线程数
    for i in range(threads_count):
        t = threading.Thread(target=fun,args=())
        threads.append(t)#添加进程
    for i in range(threads_count):
        threads[i].start()#开始进程
    for i in range(threads_count):
        threads[i].join()
if __name__ == '__main__':
    main()

运行结果:


image.png

py queue 模块

import queue

que = queue.Queue() #设置队列
for i in range(1,10):
    que.put(i)#加入队列
for i in range(1,10):
    t = que.get(i)#取出队列数据
    print(t)

输出:


image.png

将 queue 与 threading 结合

import queue
import  threading
import time
class Dofun(threading.Thread):
    def __init__(self,queue):
        threading.Thread.__init__(self)
        self._queue = queue
    def run(self):
        while not self._queue.empty():
            t = self._queue.get()
            print(t)
def main():
    threads = []#用来存储进程
    threads_count = 10#设置进程数
    que = queue.Queue()#设置队列

    for i in range(1,20):
        x = '%s:time--%s'%(str(i),time.ctime())
        que.put(x)#放入队列
    for i in range(threads_count):
        threads.append(Dofun(que))#将队列添加进程
    for i in threads:
        i.start()
    for i in threads:
        i.join()
if __name__ == '__main__':
    main()
image.png

简单的记录下

你可能感兴趣的:(python多线程)