python 多线程 入门

项目github地址:bitcarmanlee easy-algorithm-interview-and-practice
欢迎大家star,留言,一起学习进步

python里的多线程,一直用得不是很多。为了最快速的上手,搞明白多线程到底是个什么鬼,写了个简单的例子

#!/usr/bin/env python
#coding:utf-8

'''
Created on 2016年6月3日

@author: lei.wang
'''

import threading
from time import ctime,sleep

def music(entertainment):
    for i in range(2):
        print "Listening to %s. %s" %(entertainment,ctime())
        sleep(1)
        

def movie(entertainment):
    for i in range(2):
        print "Watching the %s. %s" %(entertainment,ctime())
        sleep(5)
        


if __name__ == '__main__':
    threads = []
    thread_music = threading.Thread(target=music,args=(u"暗号",))
    threads.append(thread_music)
    thread_movie = threading.Thread(target=movie,args=(u"肖圣克救赎",))
    threads.append(thread_movie)

    for each in threads:
        each.setDaemon(True)
        each.start()
    
    each.join()

    print "all threads end at %s" %(ctime())    

代码运行结果

Listening to 暗号. Fri Jun  3 12:38:12 2016
Watching the 肖圣克救赎. Fri Jun  3 12:38:12 2016
Listening to 暗号. Fri Jun  3 12:38:13 2016
Watching the 肖圣克救赎. Fri Jun  3 12:38:17 2016
all threads end at Fri Jun  3 12:38:22 2016

对代码做个简单的分析:
首先创建一个空的threads列表,用来存放线程。然后分别创建线程thread_music与thread_moive。

将Thread中源码构造函数的说明部分抠出来:

class Thread(_Verbose):
    """A class that represents a thread of control.

    This class can be safely subclassed in a limited fashion.

    """
    __initialized = False
    # Need to store a reference to sys.exc_info for printing
    # out exceptions when a thread tries to use a global var. during interp.
    # shutdown and thus raises an exception about trying to perform some
    # operation on/with a NoneType
    __exc_info = _sys.exc_info
    # Keep sys.exc_clear too to clear the exception just before
    # allowing .join() to return.
    __exc_clear = _sys.exc_clear

    def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, verbose=None):
        """This constructor should always be called with keyword arguments. Arguments are:

        *group* should be None; reserved for future extension when a ThreadGroup
        class is implemented.

        *target* is the callable object to be invoked by the run()
        method. Defaults to None, meaning nothing is called.

        *name* is the thread name. By default, a unique name is constructed of
        the form "Thread-N" where N is a small decimal number.

        *args* is the argument tuple for the target invocation. Defaults to ().

        *kwargs* is a dictionary of keyword arguments for the target
        invocation. Defaults to {}.

        If a subclass overrides the constructor, it must make sure to invoke
        the base class constructor (Thread.__init__()) before doing anything
        else to the thread.

"""

通过源码,很容易看出来
thread_music = threading.Thread(target=music,args=(u"暗号",))
是如何构造一个线程的。

jion()方法放在for循环外边,就是说必须要等for循环里的两个进程都结束以后,才能继续执行主进程。

从代码最后的结果来分析,thread_music与thread_movie是同时开始执行的,music进程sleep1s后执行第二次,而movie进程sleep5s后执行第二次。主进程在两个线程都执行完了以后才执行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值