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


运行结果:

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数组中添加一个文件,程序运行时会自动为其创建一个线程。

对if语句部分修改如下:

if __name__ == "__main__":

     for i in files:

         threads[i].start()

         print "##############"#-------添加标记

         print threads[i]#-------打印内存地址

     for i in files:

         threads[i].join()

         print '%%%%%%%%%%%%%%%'#----添加标记

         print threads[i]#-------打印内存地址

     print 'all subprocess run is over, and end:%s'%ctime()


运行代码测试结果:

[root@Python stud001]# python player.py

Start playing:爱情买卖.mp3! Tue Apr 19 11:18:12 2016

 ##############

<Thread(Thread-1, started 140538910066432)>

Start playing 阿凡达.mp4! Tue Apr 19 11:18:12 2016

##############

<Thread(Thread-2, started 140538899576576)>

Start playing:爱情买卖.mp3! Tue Apr 19 11:18:14 2016

%%%%%%%%%%%%%%%

<Thread(Thread-1, stopped 140538910066432)>

Start playing 阿凡达.mp4! Tue Apr 19 11:18:18 2016

%%%%%%%%%%%%%%%

<Thread(Thread-2, stopped 140538899576576)>

all subprocess run is over, and end:Tue Apr 19 11:18:23 2016

[root@Python stud001]# 

从输出结果可以看到,两个for循环是依次执行,当第1个for循环完成之后,再执行第2个,启用进程锁功能就是在所有子线程开启后再执行锁动作,而不是开启一个锁一个,这里要跟下面这种情况区分开来:

if __name__ == "__main__":

     for i in files:

         threads[i].start()

         threads[i].join()

         print threads[i]

         print '##########'

     print 'all subprocess run is over, and end:%s'%ctime()  

[root@Python stud001]# 

运行代码测试结果:

[root@Python stud001]# python  player.py 

Start playing:爱情买卖.mp3! Tue Apr 19 11:22:13 2016

Start playing:爱情买卖.mp3! Tue Apr 19 11:22:15 2016

<Thread(Thread-1, stopped 140470393812736)>

##########

Start playing 阿凡达.mp4! Tue Apr 19 11:22:17 2016

Start playing 阿凡达.mp4! Tue Apr 19 11:22:22 2016

<Thread(Thread-2, stopped 140470393812736)>

##########

all subprocess run is over, and end:Tue Apr 19 11:22:27 2016

[root@Python stud001]#

这里是启动一个线程就锁一个线程,跟上面正好相反。

继续改进例子:

  通过上面的程序,我们发现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






      本文转自027ryan  51CTO博客,原文链接:http://blog.51cto.com/ucode/1765299,如需转载请自行联系原作者


相关文章
|
13天前
|
安全 Java 数据处理
Python网络编程基础(Socket编程)多线程/多进程服务器编程
【4月更文挑战第11天】在网络编程中,随着客户端数量的增加,服务器的处理能力成为了一个重要的考量因素。为了处理多个客户端的并发请求,我们通常需要采用多线程或多进程的方式。在本章中,我们将探讨多线程/多进程服务器编程的概念,并通过一个多线程服务器的示例来演示其实现。
|
23天前
|
算法 数据处理 Python
Python并发编程:解密异步IO与多线程
本文将深入探讨Python中的并发编程技术,重点介绍异步IO和多线程两种常见的并发模型。通过对比它们的特点、适用场景和实现方式,帮助读者更好地理解并发编程的核心概念,并掌握在不同场景下选择合适的并发模型的方法。
|
1月前
|
并行计算 安全 Unix
Python教程第8章 | 线程与进程
本章主要讲解了线程与进程的概念,多线程的运用以及Python进程的相关案例学习
36 0
|
1月前
|
安全 Java 关系型数据库
深入探究Python的多线程与异步编程:实战与最佳实践
【2月更文挑战第1天】 深入探究Python的多线程与异步编程:实战与最佳实践
138 0
|
1月前
|
分布式计算 并行计算 Java
浅析Python自带的线程池和进程池
浅析Python自带的线程池和进程池
85 0
|
1月前
|
安全 Python
Python中的并发编程:多线程与多进程技术探究
本文将深入探讨Python中的并发编程技术,重点介绍多线程和多进程两种并发处理方式的原理、应用场景及优缺点,并结合实例分析如何在Python中实现并发编程,以提高程序的性能和效率。
|
1月前
|
数据采集 存储 Java
「多线程大杀器」Python并发编程利器:ThreadPoolExecutor,让你一次性轻松开启多个线程,秒杀大量任务!
「多线程大杀器」Python并发编程利器:ThreadPoolExecutor,让你一次性轻松开启多个线程,秒杀大量任务!
|
1月前
|
安全 调度 Python
Python中如何实现多线程?请举例说明。
Python中如何实现多线程?请举例说明。
14 0
|
7天前
|
调度 Python
Python多线程、多进程与协程面试题解析
【4月更文挑战第14天】Python并发编程涉及多线程、多进程和协程。面试中,对这些概念的理解和应用是评估候选人的重要标准。本文介绍了它们的基础知识、常见问题和应对策略。多线程在同一进程中并发执行,多进程通过进程间通信实现并发,协程则使用`asyncio`进行轻量级线程控制。面试常遇到的问题包括并发并行混淆、GIL影响多线程性能、进程间通信不当和协程异步IO理解不清。要掌握并发模型,需明确其适用场景,理解GIL、进程间通信和协程调度机制。
27 0
|
22天前
|
数据采集 Java API
python并发编程: Python使用线程池在Web服务中实现加速
python并发编程: Python使用线程池在Web服务中实现加速
18 3
python并发编程: Python使用线程池在Web服务中实现加速

热门文章

最新文章