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中signal包的使用
Nov 13 Python
Python求算数平方根和约数的方法汇总
Mar 09 Python
python实现简单登陆系统
Oct 18 Python
Python实现的对本地host127.0.0.1主机进行扫描端口功能示例
Feb 15 Python
Python学习笔记之pandas索引列、过滤、分组、求和功能示例
Jun 03 Python
python使用openCV遍历文件夹里所有视频文件并保存成图片
Jan 14 Python
python+selenium 脚本实现每天自动登记的思路详解
Mar 11 Python
Python正则表达式如何匹配中文
May 27 Python
python3+openCV 获取图片中文本区域的最小外接矩形实例
Jun 02 Python
Python openpyxl模块实现excel读写操作
Jun 30 Python
Python如何输出百分比
Jul 31 Python
python 视频下载神器(you-get)的具体使用
Jan 06 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中$美元符号与Zen Coding冲突问题解决方法分享
2014/05/28 PHP
smarty模板引擎使用内建函数foreach循环取出所有数组值的方法
2015/01/22 PHP
CentOS7.0下安装PHP5.6.30服务的教程详解
2018/09/29 PHP
超级酷和最实用的jQuery实例收集(20个)
2010/04/21 Javascript
jquery实现的横向二级导航效果代码
2015/08/26 Javascript
详解AngularJS实现表单验证
2015/12/10 Javascript
JavaScript实现点击按钮字体放大、缩小
2016/02/29 Javascript
在JavaScript中模拟类(class)及类的继承关系
2016/05/20 Javascript
基于js文件加载优化(详解)
2018/01/03 Javascript
详解Vue CLI3配置解析之css.extract
2018/09/14 Javascript
Nuxt.js 数据双向绑定的实现
2019/02/17 Javascript
vue子传父关于.sync与$emit的实现
2019/11/05 Javascript
Javascript 类型转换、封闭函数及常见内置对象操作示例
2019/11/15 Javascript
vue+element实现图片上传及裁剪功能
2020/06/29 Javascript
JavaScript实现拖拽和缩放效果
2020/08/24 Javascript
vue 中this.$set 动态绑定数据的案例讲解
2021/01/29 Vue.js
[03:09]2014DOTA2国际邀请赛 Mushi前队友送上祝福
2014/07/12 DOTA
python支持断点续传的多线程下载示例
2014/01/16 Python
spyder常用快捷键(分享)
2017/07/19 Python
Python IDLE入门简介
2017/12/08 Python
Python实现简单遗传算法(SGA)
2018/01/29 Python
Python实现统计英文文章词频的方法分析
2019/01/28 Python
Django 后台获取文件列表 InMemoryUploadedFile的例子
2019/08/07 Python
详解在Python中以绝对路径或者相对路径导入文件的方法
2019/08/30 Python
python随机模块random使用方法详解
2020/02/14 Python
PyTorch 导数应用的使用教程
2020/08/31 Python
属性与 @property 方法让你的python更高效
2020/09/21 Python
The Beach People美国:澳洲海滨奢华品牌
2018/07/05 全球购物
团日活动策划书
2014/02/01 职场文书
协议书样本
2014/04/23 职场文书
群众路线剖析材料(四风)
2014/11/05 职场文书
音乐教师个人总结
2015/02/06 职场文书
小学家长意见怎么写
2015/06/03 职场文书
关于国庆节的广播稿
2015/08/19 职场文书
十二月早安励志心语大全
2019/12/03 职场文书
Python 处理表格进行成绩排序的操作代码
2021/07/26 Python