python多线程操作实例


Posted in Python onNovember 21, 2014

一、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())

运行结果如下:

python多线程操作实例

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")
Python 相关文章推荐
Python实现扫描指定目录下的子目录及文件的方法
Jul 16 Python
Python序列之list和tuple常用方法以及注意事项
Jan 09 Python
Python3使用turtle绘制超立方体图形示例
Jun 19 Python
程序员写Python时的5个坏习惯,你有几条?
Nov 26 Python
opencv python统计及绘制直方图的方法
Jan 21 Python
Python初学者常见错误详解
Jul 02 Python
python web框架中实现原生分页
Sep 08 Python
Python 正则表达式爬虫使用案例解析
Sep 23 Python
使用pytorch实现论文中的unet网络
Jun 24 Python
python文件操作seek()偏移量,读取指正到指定位置操作
Jul 05 Python
Python机器学习工具scikit-learn的使用笔记
Jan 28 Python
Golang Web 框架Iris安装部署
Aug 14 Python
Python中的闭包详细介绍和实例
Nov 21 #Python
Python多线程同步Lock、RLock、Semaphore、Event实例
Nov 21 #Python
python多进程操作实例
Nov 21 #Python
Python多进程通信Queue、Pipe、Value、Array实例
Nov 21 #Python
Python多进程同步Lock、Semaphore、Event实例
Nov 21 #Python
Python multiprocessing.Manager介绍和实例(进程间共享数据)
Nov 21 #Python
Python pickle类库介绍(对象序列化和反序列化)
Nov 21 #Python
You might like
用PHP+java实现自动新闻滚动窗口
2006/10/09 PHP
又一个php 分页类实现代码
2009/12/03 PHP
给Function做的OOP扩展
2009/05/07 Javascript
用户注册常用javascript代码
2009/08/29 Javascript
jquery 常用操作整理 基础入门篇
2009/10/14 Javascript
Javascript this 的一些学习总结
2012/08/31 Javascript
node.js实现多图片上传实例
2014/06/03 Javascript
jQuery获取页面及个元素高度、宽度的总结——超实用
2015/07/28 Javascript
跟我学习javascript的执行上下文
2015/11/18 Javascript
JavaScript Array对象详解
2016/03/01 Javascript
详解JavaScript中this关键字的用法
2016/05/26 Javascript
微信小程序 swiper组件详解及实例代码
2016/10/25 Javascript
js仿小米手机上下滑动效果
2017/02/05 Javascript
nodejs前端自动化构建环境的搭建
2017/07/26 NodeJs
Vue底层实现原理总结
2018/02/17 Javascript
axios异步提交表单数据的几种方法
2019/08/11 Javascript
6种JavaScript继承方式及优缺点(小结)
2020/02/06 Javascript
[01:05:12]2014 DOTA2国际邀请赛中国区预选赛 TongFu VS CIS-GAME
2014/05/21 DOTA
[01:00]DOTA2 store: Collection of Artisan's Wonders
2015/08/12 DOTA
[01:02:06]LGD vs Mineski Supermajor 胜者组 BO3 第二场 6.5
2018/06/06 DOTA
简单实现python爬虫功能
2015/12/31 Python
python中根据字符串调用函数的实现方法
2016/06/12 Python
Python处理文本文件中控制字符的方法
2017/02/07 Python
python基础教程项目四之新闻聚合
2018/04/02 Python
Selenium(Python web测试工具)基本用法详解
2018/08/10 Python
django+tornado实现实时查看远程日志的方法
2019/08/12 Python
keras model.fit 解决validation_spilt=num 的问题
2020/06/19 Python
html5使用html2canvas实现浏览器截图的示例
2017/08/31 HTML / CSS
澳大利亚家居用品零售商:Harris Scarfe
2020/10/10 全球购物
高级方案规划工程师岗位职责
2013/11/29 职场文书
报到证丢失证明
2014/01/11 职场文书
葛优非诚勿扰搞笑征婚台词
2014/03/17 职场文书
我的祖国演讲稿
2014/05/04 职场文书
新闻发布会活动策划方案
2014/09/15 职场文书
教师节感谢信
2015/01/22 职场文书
2016年元旦主持词
2015/07/06 职场文书