python----多线程

单线程

顾名思义,可以理解为把一堆事情排在一起,一件一件去做,例子如下:

比如我们回到家里,先写作业,在看书或者玩游戏娱乐一下。

from time import ctime, sleep

def homework():
    for i in range(3):
        print("i am doing homework.{}".format(ctime()))
        sleep(3)
        
def play():
    for i in range(2):
        print("i am plaing.{}".format(ctime()))
        sleep(2)
        
if __name__ == '__main__':
    homework()
    play()
    print("all over.{}".format(ctime()))

所显示结果如下:

i am doing homework.Tue Dec  4 16:53:22 2018
i am doing homework.Tue Dec  4 16:53:25 2018
i am doing homework.Tue Dec  4 16:53:28 2018
i am plaing.Tue Dec  4 16:53:31 2018
i am plaing.Tue Dec  4 16:53:33 2018
all over.Tue Dec  4 16:53:35 2018

时间是逐渐叠加的,干完一件事再做另一件事。

多线程

而到了多线程就不一样了,同时可以做很多事情,就像分身一样。而python里,多线程模块主要由thread 和 threading两个库来实现。展示如下:

from time import ctime, sleep
import threading
def homework():
    for i in range(3):
        print("i am doing homework.{}".format(ctime()))
        sleep(3)
        
def play():
    for i in range(2):
        print("i am plaing.{}".format(ctime()))
        sleep(2)
        
        
threads=[]
t1=threading.Thread(target=homework)
threads.append(t1)
t2=threading.Thread(target=play)
threads.append(t2)


if __name__ == '__main__':
    for t in threads:
        t.setDaemon(True)
        t.start()
        
    

显示结果如下:

i am doing homework.Tue Dec  4 17:01:09 2018
i am plaing.Tue Dec  4 17:01:09 2018
i am plaing.Tue Dec  4 17:01:11 2018
i am doing homework.Tue Dec  4 17:01:12 2018
i am doing homework.Tue Dec  4 17:01:15 2018

在其中,我们可见首先倒入了threading模块,这是实现多线程的前提。同时创立了threads[]数组,利用target调用homework和play方法,同时可以利用args对所使用方法进行传递参数。并将创建好的线程t1装入到threads[]数组中,t2也采用同样的方法。

再通过for的方式进行遍历,setDaemon(True)将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去。

from time import ctime, sleep
import threading
def homework():
    for i in range(3):
        print("i am doing homework.{}".format(ctime()))
        sleep(3)
        
def play():
    for i in range(2):
        print("i am plaing.{}".format(ctime()))
        sleep(2)
        
        
threads=[]
t1=threading.Thread(target=homework)
threads.append(t1)
t2=threading.Thread(target=play)
threads.append(t2)


if __name__ == '__main__':
    for t in threads:
        t.setDaemon(True)
        t.start()
        
    t.join()
    print('all over.{}'.format(ctime()))
    

加入t.join()之后,可见在其中一个子线程结束之后输出结果。结果如下:

i am doing homework.Tue Dec  4 17:09:53 2018
i am plaing.Tue Dec  4 17:09:53 2018
i am plaing.Tue Dec  4 17:09:55 2018
i am doing homework.Tue Dec  4 17:09:56 2018
all over.Tue Dec  4 17:09:57 2018
i am doing homework.Tue Dec  4 17:09:59 2018

再加入一个例子 

#coding=utf-8
from time import sleep, ctime 
import threading

def muisc(func):
    for i in range(2):
        print ('Start playing: %s! %s' %(func,ctime()))
        sleep(2)
 
def move(func):
    for i in range(2):
        print ('Start playing: %s! %s' %(func,ctime()))
        sleep(5)

def player(name):
    r = name.split('.')[1]
    if r == 'mp3':
        muisc(name)
    else:
        if r == 'mp4':
            move(name)
        else:
            print ('error: The format is not recognized!')

list = ['ni.mp3','door.mp4']

threads = []
files = range(len(list))

#创建线程
for i in files:
    t = threading.Thread(target=player,args=(list[i],))
    threads.append(t)

if __name__ == '__main__': 
    #启动线程
    for i in files:
        threads[i].start() 
    for i in files:
          threads[i].join()

    #主线程
    print ('end:%s' %ctime())

显示结果如下:

Start playing: ni.mp3! Tue Dec  4 17:24:27 2018Start playing: door.mp4! Tue Dec  4 17:24:27 2018

Start playing: ni.mp3! Tue Dec  4 17:24:29 2018
Start playing: door.mp4! Tue Dec  4 17:24:32 2018
end:Tue Dec  4 17:24:37 2018

当然,上面的例子还可以继续改进

from time import ctime, sleep
import threading

def super_player(file, time):
    for i in range(2):
        print("start playing {}.{}".format(file, ctime()))
        sleep(time)
        
list={"a.mp3":3, "b.mp4":5, "c.mp3":4}

threads=[]
files=range(len(list))

for file, time in list.items():
    t=threading.Thread(target=super_player, args=(file, time))
    threads.append(t)
    
if __name__ == '__main__':
    for i in files:
        threads[i].start()
    for i in files:
        threads[i].join()
        
    print("end:{}".format(ctime()))

所显示结果如下:

start playing a.mp3.Tue Dec  4 18:44:25 2018
start playing b.mp4.Tue Dec  4 18:44:25 2018
start playing c.mp3.Tue Dec  4 18:44:25 2018
start playing a.mp3.Tue Dec  4 18:44:28 2018
start playing c.mp3.Tue Dec  4 18:44:29 2018
start playing b.mp4.Tue Dec  4 18:44:30 2018
end:Tue Dec  4 18:44:35 2018

创立自己的多线程 

import threading
from time import ctime, sleep

class my_thread(threading.Thread):
    
    def __init__(self, func, args, name=' '):
        threading.Thread.__init__(self)
        self.name=name
        self.func=func
        self.args=args
        
    def run(self):
        self.func(*self.args)        
    
def super_play(file, time):
    for i in range(2):
        print("start playing {}.{}".format(file, ctime()))
        sleep(time)
        
list = {'a.mp3':3,'b.mp4':5}

threads=[]
files=range(len(list))
for file, time in list.items():
    t=my_thread(super_play, (file, time), super_play.__name__)
    threads.append(t)
    
if __name__ == '__main__':
    for i in files:
        threads[i].start()
    for i in files:
        threads[i].join()
        
    print("end:{}".format(ctime()))

结果如下:

start playing a.mp3.Tue Dec  4 18:57:00 2018
start playing b.mp4.Tue Dec  4 18:57:00 2018
start playing a.mp3.Tue Dec  4 18:57:03 2018
start playing b.mp4.Tue Dec  4 18:57:05 2018
end:Tue Dec  4 18:57:10 2018

猜你喜欢

转载自blog.csdn.net/weixin_42307828/article/details/84791422
今日推荐