1       Python多线程

进程是程序的一次执行,每个进程都有自己的地址空间、内存、数据栈,以及其他记录其运行轨迹的辅助数据。操作系统管理在其上面运行的所有进程,并为这些进程公平地分配时间。

所有线程都运行在同一个进程中,共享相同的运行环境。可以想象成是在主进程或“主线程”中并行运行的“迷你进程”。

1.1     多线程技术

Python通过两个标准库thread和threading提供对线程的支持。Thread提供了低级别的、原始的线程以及一个简单的锁。Threading基于java的线程模型设计。锁(lock)和条件变量(condition)在java中是对象的基本行为(每一个对象都自带了锁和条件变量),而在python中则是独立的对象。

Thread不支持守护线程,threading支持守护线程,所以使用threading。

1.1.1      单线程实例

单线程:

from time import sleep, ctime

# 听音乐
def music():
    print('I was listening to music! %s' % ctime())
    sleep(2)

# 看电影
def movie():
    print('I was at the movies! %s' % ctime())
    sleep(3)

if __name__ == '__main__':
    music()
    movie()
    print('all end:', ctime())

增加循环逻辑:

from time import sleep, ctime

def music(func, loop):  #听音乐
    for i in range(loop):
        print('i was listening to music: %s! %s' % (func, ctime()))
        sleep(2)
def movie(func, loop):  # 看电影
    for i in range(loop):
        print('i was watching movie: %s! %s' % (func, ctime()))
        sleep(3)
if __name__ == '__main__':
    music('以后的以后', 2)
    movie('One Day', 2)
    print('all end:', ctime())

 

1.1.2      多线程实例

 

from time import sleep, ctime
import threading

def music(func, loop):  #听音乐
    for i in range(loop):
        print('I was listening to music: %s! %s' % (func, ctime()))
        sleep(2)
def movie(func, loop):  # 看电影
    for i in range(loop):
        print('I was watching movie: %s! %s' % (func, ctime()))
        sleep(3)

#创建线程组
threads = []

#创建线程t1,t2,并添加到线程数组
t1 = threading.Thread(target=music, args=('以后的以后', 2))
threads.append(t1)
t2 = threading.Thread(target=movie, args=('One Day', 2))
threads.append(t2)

if __name__ == '__main__':
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    print('all end: %s' % ctime())

运行结果

I was listening to music: 以后的以后! Mon May 21 16:45:51 2018
I was watching movie: One Day! Mon May 21 16:45:51 2018
I was listening to music: 以后的以后! Mon May 21 16:45:53 2018
I was watching movie: One Day! Mon May 21 16:45:54 2018
all end: Mon May 21 16:45:57 2018

Process finished with exit code 0

import threading: 引入线程模块

threads = []:创建线程数组,用于装载线程。

threading.Thread(): 通过调用threading模块的Thread()方法来创建线程。

 threads.start()开始线程活动,join()等待线程的终止。

1.1.3      多线程优化

如果每个线程都要创建一个t的话,太复杂,因此需要做如下改进:

 

from time import sleep, ctime
import threading

def player(file, time):  #播放器循环2次播放
    for i in range(2):
        print('Starting playing: %s! %s' % (file, ctime()))
        sleep(time)
#播放列表及时长
lists = {'以后的以后':3,'One Day':2,'阿甘正传':4}
#创建线程组
threads = []

for file,time in lists.items(): 
    t = threading.Thread(target=player, args =(file,time))
    threads.append(t)

if __name__ == '__main__':
    for t in range(len(lists)):
        threads[t].start()
    for t in range(len(lists)):
        threads[t].join()
    print('all end: %s' % ctime())

执行结果:

Starting playing: 以后的以后! Mon May 21 17:10:26 2018
Starting playing: One Day! Mon May 21 17:10:26 2018
Starting playing: 阿甘正传! Mon May 21 17:10:26 2018
Starting playing: One Day! Mon May 21 17:10:28 2018
Starting playing: 以后的以后! Mon May 21 17:10:29 2018
Starting playing: 阿甘正传! Mon May 21 17:10:30 2018
all end: Mon May 21 17:10:34 2018

Process finished with exit code 0

1.1.4      创建线程类(待续)

 

 
posted on 2018-05-21 17:15  jxba  阅读(256)  评论(0编辑  收藏  举报