简单的线程-threading-使用线程便捷的跑多个浏览器

        这里是清安,我们本章来一起学习一下线程。

        什么是线程?网上写了很多很多的官方属于,看的属实有点眼花缭乱,也很懵逼。

        简单的说说,线程是处理器调度的基本单位,它又跟进程有关系。一个程序至少有一个进程,一个进程至少有一个线程.。就好比我今天坐高铁从深圳到北京,有直达的,这个直达的可以看作进程,我们也可以转车从深圳抵达北京,转车的这些线路可以看作为线程。

        需要用到的模块是threading!

        首先我们先写一个单线程。

import threading
from selenium import webdriver



def work():
    fox = webdriver.Firefox()
    fox.get("https://www.baidu.com")
    fox.quit()


if __name__ == '__main__':
    th = threading.Thread(target=work)
    th.start()

        上述就是一个单线程了,其实,python本身就是单线程机制,所以,即使不这样写,运行起来依然是一个单线程。

        线程中需要告诉它你需要运行的函数时哪个,然后通过start方法,跑起来。就这样我们完成了一个单线程。

        那么我们来多个函数:

# -->>>清安<<<---
import threading
from selenium import webdriver



def work():
    fox = webdriver.Firefox()
    fox.get("https://www.baidu.com")
    fox.quit()


def time_():
    fox = webdriver.Chrome()
    fox.get("https://www.jd.com/")
    fox.quit()


def time_1():
    fox = webdriver.Chrome()
    fox.get("https://www.sina.com.cn/")
    fox.quit()


if __name__ == '__main__':
    th = threading.Thread(target=work)
    th1 = threading.Thread(target=time_)
    th2 = threading.Thread(target=time_1)

    for i in (th, th1, th2):
        i.start()
    for j in (th, th1, th2):
        j.join()

        多线程,上述代码中我们创建了三个线程,分别是th,th1,th2,然后用了for循环来启动这个多线程,那么我怎么知道它是不是真的时用了多线程来启动呢。

        多线程中有方法可以打印出对应的线程id:

    print(threading.currentThread().ident)
    print(f"ident:{threading.get_ident()}")

        这二者都可以,怎么写呢?

def time_():
    fox = webdriver.Chrome()
    print(threading.currentThread().ident)
    print(f"ident:{threading.get_ident()}")
    fox.get("https://www.jd.com/")
    fox.quit()

        同理,可以写入进去,运行之后就会看到线程ID了。

        上述中我们还用到了join方法,这个有什么用呢?

        等待,阻塞线程,直到线程执行完毕,才执行后面的代码。上述的代码中,使用的join并没有很明显的体现出来。来看另一个例子:

# -->>>清安<<<---
import threading
import time
import random


def work_a():
    for i in range(5):
        print(i, "work a", threading.get_ident())
        time.sleep(random.random() * 2)
    return "work a"


def work_b():
    for i in range(5):
        print(i, "work b", threading.get_ident())
        time.sleep(random.random() * 2)
    return "work b"


if __name__ == '__main__':
    th = threading.Thread(target=work_b)
    th1 = threading.Thread(target=work_a)
    th.start()
    th.join()

        这里,可以自己试试哦,把join去掉,跟添加一个jion。可以很明显的知道,用例join方法,其实有点类似于单线程的概念。但是不能否认的是它确实启用了两个线程,但是是一个线程跑完,另一个线程再启动的哦。

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

清安无别事

慢慢的积累一杯奶茶吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值