python多任务,线程详解

本文详细介绍了Python中的多任务实现,重点讨论了多线程的调用方式、执行顺序、线程同步以及互斥锁的概念。通过实例展示了线程如何共享全局变量,并解释了GIL全局解释器锁对多线程的影响。同时,文章提到了线程池作为后续话题。
摘要由CSDN通过智能技术生成

python 多任务

多线程

python的thread模块是⽐较底层的模块,python的threading
模块是对thread做了⼀些包装的,可以更加⽅便的被使⽤

调用

1 直接调用
# –*– coding: utf-8 –*–
# @Time      : 2019/1/7 22:21
# @Author    : Damon_duanlei
# @FileName  : thread_test01.py
# @BlogsAddr : https://blog.csdn.net/Damon_duanlei
import threading
import time


def hello_bye(name):
    print("hello! {}".format(name))
    time.sleep(1)
    print("bye! {}".format(name))


if __name__ == '__main__':
    t1 = threading.Thread(target=hello_bye, args=("臭臭",))
    t2 = threading.Thread(target=hello_bye, args=("小迪",))
    t1.start()
    t2.start()

运行结果:

>>>
hello! 臭臭
hello! 小迪
bye! 臭臭
bye! 小迪
2 继承 Threading.Thread
# –*– coding: utf-8 –*–
# @Time      : 2019/1/7 22:29
# @Author    : Damon_duanlei
# @FileName  : thread_test02.py
# @BlogsAddr : https://blog.csdn.net/Damon_duanlei

import threading
import time


def hello_bye(name):
    print("hello! {}".format(name))
    time.sleep(1)
    print("bye! {}".format(name))


class MyThread(threading.Thread):
    def __init__(self, func, name):
        threading.Thread.__init__(self)
        self.func = func
        self.name = name

    def run(self):
        self.func(self.name)


if __name__ == '__main__':
    t1 = MyThread(hello_bye, "臭臭")
    t2 = MyThread(hello_bye, "小迪")
    t1.start()
    t2.start()

运行结果:

>>>
hello! 臭臭
hello! 小迪
bye! 臭臭
bye! 小迪
区别

使用继承的方式重写run()方法,start()时不走父类的run()方法,而是走子类重写的run()方法.使用threading.Thread直接创建,start()的时候走Thread类下的run()方法,该run()方法会主动调用 target 函数. 所以使用继承方式调用多线程需要将业务逻辑写入重写后的run()方法.

线程的执行顺序

# –*– coding: utf-8 –*–
# @Time      : 2019/1/13 11:07
# @Author    : Damon_duanlei
# @FileName  : thread_runing_order.py
# @BlogsAddr : https://blog.csdn.net/Damon_duanlei

import threading
import time


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值