多线程-1-基础写法

基础

线程是调度的基本单元:

现代操作系统以线程作为调度和分派的基本单元,进程作为拥有资源的基本单位。一个进程可以包含多个线程,共享进程中内存等资源。

I/O操作性能:

对于I/O密集型任务,线程在等待I/O操作完成时会让出CPU调度,使得其他thread可以被CPU调度。

多进程:

虽然多进程不受GIL限制,但是进程的创建和销毁消耗的资源比线程要大,在I/O密集型任务场景下,关键瓶颈在于I/O设备而非CPU,所以多线程带来的并发优势已经足够,使用多进程可能会因为进程的创建和销毁带来的资源消耗导致性能下降。

multithread

多线程写法1

通过threading实例化多个线程,使用start方法启动并使用join方法使得主线程等待子线程执行。

# 多线程写法 1
import threading 
from time import sleep
import time

def get_detail_html(url):
    print("get detail html started")
    sleep(2)
    print("get detail html end")

def get_detail_url(url):
    print("get detail url started")
    sleep(2)
    print("get detail url end")

if __name__ == "__main__":
    t1 = threading.Thread(target=get_detail_html, args=("www.baidu.com",))
    t2 = threading.Thread(target=get_detail_url, args=("www.baidu.com",))
    start_time = time.time()
    t1.start()
    t2.start()
    # 使用join方法使得主线程等待线程执行完成   否则主线程不会等待子线程,就会导致,子线程执行中的时候,主线程执行时间加减
    t1.join()
    t2.join()
    end_time = time.time()
    print(end_time - start_time)
    

增加需求:当主线程退出的时候,将子线程kill掉,需要将子线程设置为守护线程

t1.setDaemon(True)
t2.setDaemon(True)

增加需求:主线程等待子线程执行完成,再进程主线程后续的代码逻辑

t1.join()
t2.join()

多线程写法 2

通过继承Thread类来实现多线程。

直接继承thread类,重写run方法。

import threading
import time
class GetDetailHtml(threading.Thread):
    def __init__(self, group = None, target = None, name = None, args = ..., kwargs = None, *, daemon = None):
        super().__init__(group, target, name, args, kwargs, daemon=daemon)
    def run(self):
        print("get detail html started")
        time.sleep(2)
        print("get detail html end")

class GetDetailUrl(threading.Thread):
    def __init__(self, group = None, target = None, name = None, args = ..., kwargs = None, *, daemon = None):
        super().__init__(group, target, name, args, kwargs, daemon=daemon)
    def run(self):
        print("get detail url started")
        time.sleep(2)
        print("get detail url end")

if __name__ == "__main__":
    t1 = GetDetailHtml()
    t2 = GetDetailUrl()
    start_time = time.time()
    t1.start()
    t2.start()
    # 使用join方法使得主线程等待线程执行完成   否则主线程不会等待子线程,就会导致,子线程执行中的时候,主线程执行时间加减
    t1.join()
    t2.join()
    end_time = time.time()
    print(end_time - start_time)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值