多任务并行之二 多线程编程

1、多线程

1.1 线程的常用方法

方法功能说明
Thread线程类,用于创建和管理线程
start()开始执行该线程
run()定义线程功能的方法(通常在子类中被重写)
join(timeout=None)直至启动的线程终止之前一直挂起;除非给出了timeout(秒),否则会一直阻塞
getName()返回线程名
setName()设定线程名
isAlivel/is_alive()布尔标志,表示这个线程是否还存活
isDaemon()判断是否是守护线程,如果是守护线程,返回True;否则,False
setDaemon(True)设置为守护线程(必须在线程start()方法之前调用)
1.1.1 多种方法创建线程
  • 创建Thread的实例,调用一个普通函数创建
  • 创建Thread的实例,调用一个类实例创建
  • 派生Thread的子类,并创建子类的实例
  1. 创建Thread的实例,调用一个普通函数创建
#!/usr/bin/env python

'''
Author: Crise
Date: 2019/11/9
'''

import threading
from time import sleep, ctime, time

loops = [8, 3, 6]


def loop(nloop, nsec):
    print("thread {0} start at: {1}".format(nloop, ctime()))
    sleep(nsec)
    print("thread {0} start at: {1}".format(nloop, ctime()))


def main():
    print("main thread starting at:", ctime())
    starttime = time()
    threads = []
    nloops = len(loops)

    for i in range(nloops):
        t = threading.Thread(target=loop, args=(i, loops[i]))
        threads.append(t)

    for thread in threads:
        thread.start()
        # thread.join() # 若在这设置join()方法会等线程1执行完才执行其他线程

    for thread in threads:
        thread.join()

    print('all done at:', ctime())
    print('main thread end, total time spend: ', time() - starttime)


if __name__ == "__main__":
    main()

'''
main thread starting at: Sat Nov  9 21:43:44 2019
thread 0 start at: Sat Nov  9 21:43:44 2019
thread 1 start at: Sat Nov  9 21:43:44 2019
thread 2 start at: Sat Nov  9 21:43:44 2019
thread 1 start at: Sat Nov  9 21:43:47 2019
thread 2 start at: Sat Nov  9 21:43:50 2019
thread 0 start at: Sat Nov  9 21:43:52 2019
all done at: Sat Nov  9 21:43:52 2019
main thread end, total time spend:  8.001137495040894

'''
  1. 创建Thread的实例,调用一个类实例创建
#!/usr/bin/env python

'''
Author: Crise
Date: 2019/11/9
'''

import threading
from time import time, sleep, ctime

loops = [4, 1, 9]


class ThreadFunc(object):

    def __init__(self, func, args, name=''):
        self.func = func
        self.args = args
        self.name = name

    def __call__(self):
        self.func(*self.args)


def loop(nloop, nsec):
    print("thread {0} start at: {1}".format(nloop, ctime()))
    sleep(nsec)
    print("thread {0} start at: {1}".format(nloop, ctime()))


def main():
    print('main thread start at:', ctime())
    starttime = time()
    threads = []

    for i in range(len(loops)):
        t = threading.Thread(
            target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
        threads.append(t)

    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    print('all done at:', ctime())
    print('main thread end, total time spend: ', time() - starttime)


if __name__ == "__main__":
    main()

'''
main thread start at: Sat Nov  9 21:47:18 2019
thread 0 start at: Sat Nov  9 21:47:18 2019
thread 1 start at: Sat Nov  9 21:47:18 2019
thread 2 start at: Sat Nov  9 21:47:18 2019
thread 1 start at: Sat Nov  9 21:47:19 2019
thread 0 start at: Sat Nov  9 21:47:22 2019
thread 2 start at: Sat Nov  9 21:47:27 2019
all done at: Sat Nov  9 21:47:27 2019
main thread end, total time spend:  9.00260877609253

'''    
    
  1. 派生Thread的子类,通过重写Thread类的__init__和run()方法,创建线程对象之后,当调用start()方法会自动调用该类对象的run()方法,创建线程
#!/usr/bin/env python

'''
Author: Crise
Date: 2019/11/9
'''

import threading
from time import time, sleep, ctime

loops = [4, 2, 6]


class MyThread(threading.Thread):

    def __init__(self, func, args, name=''):
        super(MyThread, self).__init__()
        self.name = name
        self.func = func
        self.args = args

    def run(self):
        self.func(*self.args)


def loop(nloop, nsec):
    print("thread {0} start at: {1}".format(nloop, ctime()))
    sleep(nsec)
    print("thread {0} start at: {1}".format(nloop, ctime()))


def main():
    print("main thread starting at:", ctime())
    starttime = time()
    threads = []

    for i in range(len(loops)):
        t = MyThread(loop, (i, loops[i]), loop.__name__)
        threads.append(t)

    for thread in threads:
        thread.start()

    for thread in threads:
        thread.join()

    print('all done at:', ctime())
    print('main thread end, total time spend: ', time() - starttime)


if __name__ == "__main__":
    main()

'''
main thread starting at: Sat Nov  9 21:48:26 2019
thread 0 start at: Sat Nov  9 21:48:26 2019
thread 1 start at: Sat Nov  9 21:48:26 2019
thread 2 start at: Sat Nov  9 21:48:26 2019
thread 1 start at: Sat Nov  9 21:48:28 2019
thread 0 start at: Sat Nov  9 21:48:30 2019
thread 2 start at: Sat Nov  9 21:48:32 2019
all done at: Sat Nov  9 21:48:32 2019
main thread end, total time spend:  6.00217604637146

'''
1.1.2 统计线程
1.1.3 守护线程
1.2 线程调度与同步

在实际开发中,不仅要合理控制线程数量,还需要在多个线程之间进行有效地同步和调度才能发挥最大效率。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值