python threading模块操作多线程介绍


Posted in Python onApril 08, 2015

python是支持多线程的,并且是native的线程。主要是通过thread和threading这两个模块来实现的。thread是比较底层的模块,threading是对thread做了一些包装的,可以更加方便的被使用。这里需要提一下的是python对线程的支持还不够完善,不能利用多CPU,但是下个版本的python中已经考虑改进这点,让我们拭目以待吧。

    threading模块里面主要是对一些线程的操作对象化了,创建了叫Thread的class。一般来说,使用线程有两种模式,一种是创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行;另一种是直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的class里。我们来看看这两种做法吧。

#-*- encoding: gb2312 -*-
import string, threading, time

def thread_main(a):
  global count, mutex
  # 获得线程名
  threadname = threading.currentThread().getName()
  
  for x in xrange(0, int(a)):
    # 取得锁
    mutex.acquire()
    count = count + 1
    # 释放锁
    mutex.release()
    print threadname, x, count
    time.sleep(1)
  
def main(num):
  global count, mutex
  threads = []
  
  count = 1
  # 创建一个锁
  mutex = threading.Lock()
  # 先创建线程对象
  for x in xrange(0, num):
    threads.append(threading.Thread(target=thread_main, args=(10,)))
  # 启动所有线程
  for t in threads:
    t.start()
  # 主线程中等待所有子线程退出
  for t in threads:
    t.join() 
  
  
if __name__ == '__main__':
  num = 4
  # 创建4个线程
  main(4)

上面的就是第一种做法,这种做法是很常见的,下面是另一种,曾经使用过Java的朋友应该很熟悉这种模式:

#-*- encoding: gb2312 -*-
import threading
import time

class Test(threading.Thread):
  def __init__(self, num):
    threading.Thread.__init__(self)
    self._run_num = num
  
  def run(self):
    global count, mutex
    threadname = threading.currentThread().getName()
  
    for x in xrange(0, int(self._run_num)):
      mutex.acquire()
      count = count + 1
      mutex.release()
      print threadname, x, count
      time.sleep(1)

if __name__ == '__main__':
  global count, mutex
  threads = []
  num = 4
  count = 1
  # 创建锁
  mutex = threading.Lock()
  # 创建线程对象
  for x in xrange(0, num):
    threads.append(Test(10))
  # 启动线程
  for t in threads:
    t.start()
  # 等待子线程结束
  for t in threads:
    t.join()
Python 相关文章推荐
跟老齐学Python之集合的关系
Sep 24 Python
简单介绍Python中利用生成器实现的并发编程
May 04 Python
python字典DICT类型合并详解
Aug 17 Python
Python使用pickle模块报错EOFError Ran out of input的解决方法
Aug 16 Python
详解多线程Django程序耗尽数据库连接的问题
Oct 08 Python
python3 字符串/列表/元组(str/list/tuple)相互转换方法及join()函数的使用
Apr 03 Python
python的内存管理和垃圾回收机制详解
May 18 Python
python算法与数据结构之冒泡排序实例详解
Jun 22 Python
python 搜索大文件的实例代码
Jul 08 Python
python模拟鼠标点击和键盘输入的操作
Aug 04 Python
浅谈pytorch 模型 .pt, .pth, .pkl的区别及模型保存方式
May 25 Python
详解非极大值抑制算法之Python实现
Jun 28 Python
Python使用scrapy采集数据时为每个请求随机分配user-agent的方法
Apr 08 #Python
python中Genarator函数用法分析
Apr 08 #Python
探索Python3.4中新引入的asyncio模块
Apr 08 #Python
Windows下用py2exe将Python程序打包成exe程序的教程
Apr 08 #Python
Python bsddb模块操作Berkeley DB数据库介绍
Apr 08 #Python
Python使用scrapy采集数据过程中放回下载过大页面的方法
Apr 08 #Python
在Python中使用M2Crypto模块实现AES加密的教程
Apr 08 #Python
You might like
php数组操作之键名比较与差集、交集赋值的方法
2014/11/10 PHP
PHP中foreach()用法汇总
2015/07/02 PHP
jquery 经典动画菜单效果代码
2010/01/26 Javascript
利用百度地图JSAPI生成h7n9禽流感分布图实现代码
2013/04/15 Javascript
js为鼠标添加右击事件防止默认的右击菜单弹出
2013/07/29 Javascript
上传图片预览JS脚本 Input file图片预览的实现示例
2014/10/23 Javascript
jQuery通过扩展实现抖动效果的方法
2015/03/11 Javascript
60行js代码实现俄罗斯方块
2015/03/31 Javascript
详解Bootstrap创建表单的三种格式(一)
2016/01/04 Javascript
JavaScript实现复制内容到粘贴板代码
2016/03/31 Javascript
利用JQuery阻止事件冒泡
2016/12/01 Javascript
JavaScript数据结构之单链表和循环链表
2017/11/28 Javascript
vue页面离开后执行函数的实例
2018/03/13 Javascript
详解Require.js与Sea.js的区别
2018/08/05 Javascript
解决vue-cli webpack打包开启Gzip 报错问题
2019/07/24 Javascript
Javascript中的this,bind和that使用实例
2019/12/05 Javascript
Python中scatter函数参数及用法详解
2017/11/08 Python
selenium python浏览器多窗口处理代码示例
2018/01/15 Python
python使用锁访问共享变量实例解析
2018/02/08 Python
利用 Flask 动态展示 Pyecharts 图表数据方法小结
2019/09/04 Python
python设置环境变量的作用整理
2020/02/17 Python
浅析python 字典嵌套
2020/09/29 Python
CSS3选择器新增问题的实现
2021/01/21 HTML / CSS
MAC Cosmetics巴西官方网站:M·A·C彩妆
2019/04/18 全球购物
Loreto Gallo英国:欧洲领先的在线药房
2021/01/21 全球购物
专科毕业生就业推荐信
2013/11/01 职场文书
大学生求职信
2014/06/17 职场文书
解放思想演讲稿
2014/09/11 职场文书
党的群众路线教育实践活动制度建设计划
2014/11/03 职场文书
投资公司董事长岗位职责
2015/04/16 职场文书
2015上半年个人工作总结
2015/07/27 职场文书
总结几个非常实用的Python库
2021/06/26 Python
详细聊聊MySQL中慢SQL优化的方向
2021/08/30 MySQL
SpringBoot集成Redis的思路详解
2021/10/16 Redis
一篇文章看懂MySQL主从复制与读写分离
2021/11/07 MySQL
CentOS7安装MySQL8的超级详细教程(无坑!)
2022/06/10 Servers