python 多线程就这么简单(续)

简介:

  之前讲了多线程的一篇博客,感觉讲的意犹未尽,其实,多线程非常有意思。因为我们在使用电脑的过程中无时无刻都在多进程和多线程。我们可以接着之前的例子继续讲。请先看我的上一篇博客。

python 多线程就这么简单

  从上面例子中发现线程的创建是颇为麻烦的,每创建一个线程都需要创建一个txt1t2...),如果创建的线程多时候这样极其不方便。下面对通过例子进行继续改进:

player.py

#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 = ['爱情买卖.mp3','阿凡达.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()

 

  有趣的是我们又创建了一个player()函数,这个函数用于判断播放文件的类型。如果是mp3格式的,我们将调用music()函数,如果是mp4格式的我们调用move()函数。哪果两种格式都不是那么只能告诉用户你所提供有文件我播放不了。

  然后,我们创建了一个list的文件列表,注意为文件加上后缀名。然后我们用len(list) 来计算list列表有多少个文件,这是为了帮助我们确定循环次数。

  接着我们通过一个for循环,把list中的文件添加到线程中数组threads[]中。接着启动threads[]线程组,最后打印结束时间。

     split()可以将一个字符串拆分成两部分,然后取其中的一部分。

 

>>> x = 'testing.py'
>>> s = x.split('.')[1]
>>> if s=='py':
    print s

    
py

 

 

 

运行结果:



Start playing: 爱情买卖.mp3! Mon Apr 21 12:48:40 2014
Start playing: 阿凡达.mp4! Mon Apr 21 12:48:40 2014
Start playing: 爱情买卖.mp3! Mon Apr 21 12:48:42 2014
Start playing: 阿凡达.mp4! Mon Apr 21 12:48:45 2014
end:Mon Apr 21 12:48:50 2014

现在向list数组中添加一个文件,程序运行时会自动为其创建一个线程。

 

继续改进例子:

  通过上面的程序,我们发现player()用于判断文件扩展名,然后调用music()move() ,其实,music()move()完整工作是相同的,我们为什么不做一台超级播放器呢,不管什么文件都可以播放。经过改造,我的超级播放器诞生了。

super_player.py

 

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

def super_player(file,time):
    for i in range(2):
        print 'Start playing: %s! %s' %(file,ctime())
        sleep(time)

#播放的文件与播放时长
list = {'爱情买卖.mp3':3,'阿凡达.mp4':5,'我和你.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:%s' %ctime()

 

  首先创建字典list ,用于定义要播放的文件及时长(秒),通过字典的items()方法来循环的取filetime,取到的这两个值用于创建线程。

  接着创建super_player()函数,用于接收filetime,用于确定要播放的文件及时长。

  最后是线程启动运行。运行结果:

Start playing: 爱情买卖.mp3! Fri Apr 25 09:45:09 2014
Start playing: 我和你.mp3! Fri Apr 25 09:45:09 2014
Start playing: 阿凡达.mp4! Fri Apr 25 09:45:09 2014
Start playing: 爱情买卖.mp3! Fri Apr 25 09:45:12 2014
Start playing: 我和你.mp3! Fri Apr 25 09:45:13 2014
Start playing: 阿凡达.mp4! Fri Apr 25 09:45:14 2014
end:Fri Apr 25 09:45:19 2014

 

创建自己的多线程类

 

#coding=utf-8
import threading 
from time import sleep, ctime 
 
class MyThread(threading.Thread):

    def __init__(self,func,args,name=''):
        threading.Thread.__init__(self)
        self.name=name
        self.func=func
        self.args=args
    
    def run(self):
        apply(self.func,self.args)


def super_play(file,time):
    for i in range(2):
        print 'Start playing: %s! %s' %(file,ctime())
        sleep(time)


list = {'爱情买卖.mp3':3,'阿凡达.mp4':5}

#创建线程
threads = []
files = range(len(list))

for k,v in list.items():
    t = MyThread(super_play,(k,v),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:%s' %ctime()

MyThread(threading.Thread)

创建MyThread类,用于继承threading.Thread类。

 

__init__()

使用类的初始化方法对funcargsname等参数进行初始化。  

apply()

  apply(func [, args [, kwargs ]]) 函数用于当函数参数已经存在于一个元组或字典中时,间接地调用函数。args是一个包含将要提供给函数的按位置传递的参数的元组。如果省略了args,任何参数都不会被传递,kwargs是一个包含关键字参数的字典。

apply() 用法:

 

#不带参数的方法
>>> def say():
    print 'say in'

>>> apply(say)
say in

#函数只带元组的参数
>>> def say(a,b):
    print a,b

>>> apply(say,('hello','虫师'))
hello 虫师

#函数带关键字参数
>>> def say(a=1,b=2):
    print a,b

    
>>> def haha(**kw):
    apply(say,(),kw)

    
>>> haha(a='a',b='b')
a b

 

MyThread(super_play,(k,v),super_play.__name__)

由于MyThread类继承threading.Thread类,所以,我们可以使用MyThread类来创建线程。

运行结果:

Start playing: 爱情买卖.mp3! Fri Apr 25 10:36:19 2014
Start playing: 阿凡达.mp4! Fri Apr 25 10:36:19 2014
Start playing: 爱情买卖.mp3! Fri Apr 25 10:36:22 2014
Start playing: 阿凡达.mp4! Fri Apr 25 10:36:24 2014
all end: Fri Apr 25 10:36:29 2014

目录
相关文章
|
8月前
|
Python
|
3月前
|
Python
Python的多线程
Python的多线程
35 0
|
5月前
|
Python
python 简单的多线程代码
python 简单的多线程代码
31 0
|
8月前
|
Python
|
9月前
|
安全 Python
Python3 多线程
Python3 多线程
|
安全 Python
Python 多线程
Python 多线程
45 0
Python 多线程
|
数据采集 调度 C++
python 多线程
python 多线程
|
安全 Java 调度
Python 编程 | 连载 26 - Python 多线程
Python 编程 | 连载 26 - Python 多线程
Python 编程 | 连载 26 - Python 多线程
|
安全 Java API
第48天:初识 Python 多线程
第48天:初识 Python 多线程
125 0
|
监控 Python 调度
python之多线程
注:本文是廖大的教程文章,本人也在学习,因为老是记不住,自己手打一边,代码也是亲自测试。廖大传送门 多进程 多个任务可以由多进程完成,也可以由一个进程内的多线程完成。
1308 0