您的位置:首页 > 编程语言 > Python开发

Python 多线程(threading模块)

2014-10-26 13:28 387 查看
首先,自己区分单线程和多线程的概念,自己去搜

单线程的例子如下:

__author__ = 'MrChen'

import threading
from time import ctime, sleep
#单线程
def music(music_name, length):
    for i in range(4):
        print('I was listening to %s %s' % (music_name, ctime()))
        sleep(length)

def movie(movie_name, length):
    for i in range(2):
        print('I was at the movie %s %s' % (movie_name, ctime()))
        sleep(length)

if __name__ == '__main__':
    music('腐草为萤', 2)
    movie('大话西游', 4)
    print('all over %s' % ctime())


运行结果如下:

I was listening to 腐草为萤 Sun Oct 26 13:07:51 2014
I was listening to 腐草为萤 Sun Oct 26 13:07:53 2014
I was listening to 腐草为萤 Sun Oct 26 13:07:55 2014
I was listening to 腐草为萤 Sun Oct 26 13:07:57 2014
I was at the movie 大话西游 Sun Oct 26 13:07:59 2014
I was at the movie 大话西游 Sun Oct 26 13:08:03 2014
all over Sun Oct 26 13:08:07 2014


多线程的例子如下:

__author__ = 'MrChen'

import threading
from time import ctime, sleep
#多线程
def music(music_name, length):
    for i in range(4):
        print('I was listening to %s %s' % (music_name, ctime()))
        sleep(length)

def movie(movie_name, length):
    for i in range(2):
        print('I was at the movie %s %s' % (movie_name, ctime()))
        sleep(length)

th1 = threading.Thread(target=music, args=('腐草为萤',1))
th2 = threading.Thread(target=movie, args=('大话西游',2))
threads = [th1, th2]

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


运行结果如下:

I was listening to 腐草为萤 Sun Oct 26 13:09:16 2014
I was at the movie 大话西游 Sun Oct 26 13:09:16 2014
I was listening to 腐草为萤 Sun Oct 26 13:09:17 2014
I was listening to 腐草为萤 Sun Oct 26 13:09:18 2014
I was at the movie 大话西游 Sun Oct 26 13:09:18 2014
I was listening to 腐草为萤 Sun Oct 26 13:09:19 2014
all over Sun Oct 26 13:09:20 2014


threading是python标准库中的模块,有些朋友查到会有thread这个模块,但是在python3里面只剩下threading这个模块了,因为threading模块用起来更简单也更安全一些

至于time模块,以后再讲,这里只需要知道time模块中有ctime(),sleep()等函数即可,ctime()返回当前时间,用一个str表示,sleep(n)表示挂起n秒



下面重点解释上面代码是怎么回事:



import threading

导入threading模块



th1 = threading.Thread(target=music, args=('腐草为萤',1))

创建一个线程th1,threading.Thread()是一个类,类的构造函数原型如下:

class threading.Thread(group=None,target=None, name=None, args=(), kwargs={}, *, daemon=None)
这里用到了target,表示要调用的函数名,args表示调用函数的参数

threads = [th1, th2]

将两个线程放入一个列表中

for t in threads:

t.setDaemon(True)

t.start()

t.join()

最后使用一个for循环,依次将列表中的线程开启
t.setDaemon(True)

将线程声明为守护线程,必须在start() 方法调用之前设置,如果不设置为守护线程程序会被无限挂起。子线程启动后,父线程也继续执行下去,当父线程执行完最后一条语句print "all over %s" %ctime()后,没有等待子线程,直接就退出了,同时子线程也一同结束。

t.start()

开始线程活动。

t.join()

join()方法,用于等待线程终止。join()的作用是,在子线程完成运行之前,这个子线程的父线程将一直等待。

注意: join()方法的位置是在for循环外的,也就是说必须等待for循环里的两个进程都结束后,才去执行主进程。如果没有join()函数,那么父线程执行完之后就会立即结束,不会等待子线程执行完
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: