Python线程——单线程和多线程的创建以及测试

1、Python单线程

python的线程需要导入threading包,一般默认都有的,具体创建单线程并测试代码如下

import threading
import time

def test(hostpool):
    for i in range(5):
        print("test:",i," ",hostpool)
        time.sleep(1)
    
thread=threading.Thread(target=test,kwargs={"hostpool":"def"})
# target是线程调用的函数,kwargs是传给target函数的参数名称字典

thread.start()
# 开启线程

2、Python多线程

由于测试的需要,需要在多线程内加入定时任务,这里采用的是schedule模块来辅助实现相关功能
测试代码如下:

import schedule
import time
import datetime
import threading

def test(hostpool):
	# 实际被调用的函数
    print("------",hostpool,":",datetime.datetime.now())

def test_predict(hostpool):
    # 定时任务
    schedule.every(10).seconds.do(test,{"hostpool":hostpool})
    while True:
        schedule.run_pending()
        time.sleep(1)


if __name__ == '__main__':
    f=open("hostpool.txt")
    data=f.readlines()
    hostpools=[]
    for d in data:
        hostpool=d.split("-")[0]
        hostpools.append(hostpool)
    
    # 创建线程池并启动
    threadpool=[]
    for hostpool in hostpools:
        th=threading.Thread(target=test_predict,kwargs={"hostpool":hostpool})
        threadpool.append(th)
    for th in threadpool:
        th.start()
    for th in threadpool:
        threading.Thread.join(th)
    

展示结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值