python多线程操作实例
作者:junjie 发布时间:2022-09-22 12:21:34
一、python多线程
因为CPython的实现使用了Global Interpereter Lock(GIL),使得python中同一时刻只有一个线程在执行,从而简化了python解释器的实现,且python对象模型天然地线程安全。如果你想你的应用程序在多核的机器上使用更好的资源,建议使用multiprocessing或concurrent.futures.processpoolexecutor。但是如果你的程序是IO密集型,则使用线程仍然是很好的选择。
二、python多线程使用的两种方法
实例:
import threading
import time
def worker(num):
print (threading.currentThread().getName() + ' start')
time.sleep(10)
print (threading.currentThread().getName() + ' running')
print (threading.currentThread().getName() + " " + str(num))
print (threading.currentThread().getName() + ' exit')
def deamon():
print (threading.currentThread().getName() + ' start')
time.sleep(20)
print (threading.currentThread().getName() + ' running')
print (threading.currentThread().getName() + ' exit')
print(threading.currentThread().getName())
d = threading.Thread(name='deamon', target=deamon)
d.setDaemon(True)
d.start()
w = threading.Thread(name='worker', target=worker, args=(10,))
w.start()
class myWorker(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
self.thread_stop = False
def run(self):
print (self.getName()+' start')
time.sleep(30)
print (self.getName()+' running')
print (self.getName()+" " + str(self.num))
print (self.getName()+' exit')
mw = myWorker(30)
mw.setName("MyWorker")
mw.start()
print(threading.currentThread().getName())
print("All threads:")
print("------------")
for th in threading.enumerate():
print(th.getName())
print("------------")
d.join()
w.join()
mw.join()
print(threading.currentThread().getName())
运行结果如下:
1)python线程使用的两种方法:
**直接调用threading.Thread来构造thread对象,Thread的参数如下:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
group为None;
target为线程将要执行的功能函数;
name为线程的名字,也可以在对象构造后调用setName()来设定;
args为tuple类型的参数,可以为多个,如果只有一个也的使用tuple的形式传入,例如(1,);
kwargs为dict类型的参数,也即位命名参数;
**实现自己的threading.Thread的子类,需要重载__init__()和run()。
2)threading.Thread对象的其他方法:
start(),用来启动线程;
join(), 等待直到线程结束;
setDeamon(), 设置线程为deamon线程,必须在start()调用前调用,默认为非demon。
注意: python的主线程在没有非deamon线程存在时就会退出。
3)threading的静态方法:
threading.current_thread() , 用来获得当前的线程;
threading.enumerate() , 用来多的当前存活的所有线程;
threading.Timer 定时器,其实是thread的一个字类型,使用如下:
def hello(): print("hello, world")
t = Timer(30.0, hello)
t.start()
4)logging是线程安全的
logging 模块是线程安全的,所以可以使用logging来帮助调试多线程程序。
import logging
logging.basicConfig(level=logging.DEBUG,
format="(%(threadName)-10s : %(message)s",
)
logging.debug("wait_for_event_timeout starting")


猜你喜欢
- It is much easier to criticize somebody else’s work than to create som
- 一行代码实现灰度图抠图抠图是ps的最基本技能,利用python可以实现用一行代码实现灰度图抠图。基础算法是确定图像二值化分割阈值的大津法,将
- 前言前面有篇文章我们学习了 Go 语言空结构体详解,最近又在看 unsafe包的知识,在查阅相关资料时不免会看到内存对齐相关的内容
- 装饰器模式在以下场景中被广泛应用:动态地向对象添加职责或行为,而不需要更改对象的代码。例如,可以通过装饰器模式来实现日志记录、性能分析、缓存
- 这篇文章主要介绍了如何基于python实现归一化处理,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友
- 在自己的网站主页上增加社会化分享按钮,是有效提高自己网站流量的一种方法。今天我在无争围棋网上增加了社会化按钮,根据我个人的习惯,我选择了豆瓣
- 内容介绍将日常工作中遇到的数数据冲突和样本源的方法进行总结,其中主要包括实际业务数据冲突、样本选取问题、数据共线性 等思路,并且长期更新。实
- 前言:大家跟我一起念,Python * 好,跟着本宝宝用Python抢火车票首先我们需要splinter安装:pip install spli
- <div id="d1"></div> <script > fu
- 一. valid卷积的梯度我们分两种不同的情况讨论valid卷积的梯度:第一种情况,在已知卷积核的情况下,对未知张量求导(即对张量中每一个变
- SVG是XML来描述二维图形的语言。SVG可以构造3种类型的图形对象:矢量图形、位图图象和文字。图形对象可被组化、样式化、变形和重组,包括图
- 入门scipy.optimize中,curve_fit函数可调用非线性最小二乘法进行函数拟合,例如,现在有一个高斯函数想要被拟合则调用方法如
- 本教程主要介绍css的基础知识,将逐个讲解css的各个属性,过程可能比较枯燥,但会尽力多举例说明.作者的网站:http://jorux.co
- 官方示例:uni-popup 弹出层 - DCloud 插件市场弹出层组件用于弹出一个覆盖到页面上的内容,使用场景如:底部弹出分
- PHP输出JSON格式数据常用框架封装好的方法来输出JSON数据,但是手动去书写的时候却遇到了问题,因为输出的数据类型为字符串类型,导致不能
- 一对多(ForeignKey)class ForeignKey(ForeignObject): def __init__(sel
- 前言本文主要分享一个python代码,可以将多个视频中的音频转化为相同采样率的视频。对视频格式的校验没有做,也不是很关键。环境依赖ffmpe
- 1 plot 函数语法plot:绘制二维线图NO.1 绘制横轴为X,竖轴为Y二维线图,Y值与X值一一对应。plot(X,Y)如果 X 和 Y
- 一、前言最近经常碰到开发误删除误更新数据,这不,他们又给我找了个麻烦,我们来看下整个过程。二、过程由于开发需要在生产环节中修复数据,需要执行
- 时钟实现实现这个时钟时间需要解决以下三个问题:获得当前时间,并格式化如何可以在页面中显示时间让时间动起来1、获得当前时间,并格式化要获得当前