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 相关文章推荐
2款Python内存检测工具介绍和使用方法
Jun 01 Python
使用Python编写一个在Linux下实现截图分享的脚本的教程
Apr 24 Python
Python openpyxl 遍历所有sheet 查找特定字符串的方法
Dec 10 Python
从运行效率与开发效率比较Python和C++
Dec 14 Python
简单了解django索引的相关知识
Jul 17 Python
Python基础之字典常见操作经典实例详解
Feb 26 Python
Django静态资源部署404问题解决方案
May 11 Python
Python xpath表达式如何实现数据处理
Jun 13 Python
Python代码需要缩进吗
Jul 01 Python
使用Python封装excel操作指南
Jan 29 Python
详解python的xlwings库读写excel操作总结
Feb 26 Python
Python通过loop.run_in_executor执行同步代码 同步变为异步
Apr 11 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通过字符串调用函数示例
2014/03/02 PHP
Codeigniter购物车类不能添加中文的解决方法
2014/11/29 PHP
老生常谈PHP面向对象之注册表模式
2017/05/26 PHP
jquery学习笔记二 实现可编辑的表格
2010/04/09 Javascript
js自动闭合html标签(自动补全html标记)
2012/10/04 Javascript
javascript阻止浏览器后退事件防止误操作清空表单
2013/11/22 Javascript
js调试工具Console命令详解
2014/10/21 Javascript
javascript简单实现图片预加载
2014/12/03 Javascript
node.js中的fs.write方法使用说明
2014/12/15 Javascript
JQuery select(下拉框)操作方法汇总
2015/04/15 Javascript
jQuery插件datepicker 日期连续选择
2015/06/12 Javascript
jQuery实现TAB风格的全国省份城市滑动切换效果代码
2015/08/24 Javascript
js实现显示当前状态的导航效果代码
2015/08/28 Javascript
javascript三种代码注释方法
2016/06/02 Javascript
jQuery实现的导航下拉菜单效果示例
2016/09/05 Javascript
axios向后台传递数组作为参数的方法
2018/08/11 Javascript
element-ui 表格数据时间格式化的方法
2018/08/24 Javascript
原生JS实现获取及修改CSS样式的方法
2018/09/04 Javascript
小程序开发之模态框组件封装
2020/04/23 Javascript
python在多玩图片上下载妹子图的实现代码
2013/08/13 Python
从零学python系列之从文件读取和保存数据
2014/05/23 Python
Python外星人入侵游戏编程完整版
2020/03/30 Python
Python模拟登陆实现代码
2017/06/14 Python
python内置函数:lambda、map、filter简单介绍
2017/11/16 Python
为什么从Python 3.6开始字典有序并效率更高
2019/07/15 Python
基于Pycharm加载多个项目过程图解
2020/01/19 Python
python 根据列表批量下载网易云音乐的免费音乐
2020/12/03 Python
H5 meta小结(前端必看篇)
2016/08/24 HTML / CSS
小学一年级评语大全
2014/04/22 职场文书
产品发布会策划方案
2014/05/12 职场文书
美术专业自荐信
2014/07/07 职场文书
商场父亲节活动方案
2014/08/27 职场文书
涨工资申请书应该怎么写?
2019/07/08 职场文书
详解MySQL 联合查询优化机制
2021/05/10 MySQL
springboot利用redis、Redisson处理并发问题的操作
2021/06/18 Java/Android
nginx结合openssl实现https的方法
2021/07/25 Servers