python: 多线程实现的两种方式及让多条命令并发执行
一 概念介绍
Thread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;另一种是创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入.
Thread模块是比较底层的模块,Threading模块是对Thread做了一些包装的,可以更加方便的被使用。
另外在工作时,有时需要让多条命令并发的执行, 而不是顺序执行.
有关线程的详细介绍,请参考官方文档 https://docs.python.org/2/library/threading.html
二 代码样例
#!/usr/bin/python
# encoding=utf-8
# Filename: thread-extends-class.py
# 直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里
import threading
import timeclass ThreadImpl(threading.Thread):def __init__(self, num):threading.Thread.__init__(self)self._num = numdef run(self):global total, mutex# 打印线程名print threading.currentThread().getName()for x in xrange(0, int(self._num)):# 取得锁mutex.acquire()total = total + 1# 释放锁mutex.release()if __name__ == '__main__':#定义全局变量global total, mutextotal = 0# 创建锁mutex = threading.Lock()#定义线程池threads = []# 创建线程对象for x in xrange(0, 40):threads.append(ThreadImpl(100))# 启动线程for t in threads:t.start()# 等待子线程结束for t in threads:t.join() # 打印执行结果print total
#!/usr/bin/python
# encoding=utf-8
# Filename: thread-function.py
# 创建线程要执行的函数,把这个函数传递进Thread对象里,让它来执行import threading
import timedef threadFunc(num):global total, mutex# 打印线程名print threading.currentThread().getName()for x in xrange(0, int(num)):# 取得锁mutex.acquire()total = total + 1# 释放锁mutex.release()def main(num):#定义全局变量global total, mutextotal = 0# 创建锁mutex = threading.Lock()#定义线程池threads = []# 先创建线程对象for x in xrange(0, num):threads.append(threading.Thread(target=threadFunc, args=(100,)))# 启动所有线程for t in threads:t.start()# 主线程中等待所有子线程退出for t in threads:t.join() # 打印执行结果print totalif __name__ == '__main__':# 创建40个线程main(40)
#!/usr/bin/python
# encoding=utf-8
# Filename: put_files_hdfs.py
# 让多条命令并发执行,如让多条scp,ftp,hdfs上传命令并发执行,提高程序运行效率
import datetime
import os
import threadingdef execCmd(cmd):try:print "命令%s开始运行%s" % (cmd,datetime.datetime.now())os.system(cmd)print "命令%s结束运行%s" % (cmd,datetime.datetime.now())except Exception, e:print '%s\t 运行失败,失败原因\r\n%s' % (cmd,e)if __name__ == '__main__':# 需要执行的命令列表cmds = ['ls /root','pwd',]#线程池threads = []print "程序开始运行%s" % datetime.datetime.now()for cmd in cmds:th = threading.Thread(target=execCmd, args=(cmd,))th.start()threads.append(th)# 等待线程运行完毕for th in threads:th.join()print "程序结束运行%s" % datetime.datetime.now()
python: 多线程实现的两种方式及让多条命令并发执行相关推荐
- python 并发执行命令_python: 多线程实现的两种方式及让多条命令并发执行
一 概念介绍 Thread 是threading模块中最重要的类之一,可以使用它来创建线程.有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法:另一种是创建一个threading. ...
- Py之qrcode:调用python的qrcode库两种方式生成二维码、带logo的二维码
Py之qrcode:调用python的qrcode库两种方式生成二维码.带logo的二维码 目录 python编程实现生成二维码 1.第一种方式-纯文本 2.第二种方式-带logo
- 运用python的方式_对Python使用mfcc的两种方式详解
1.Librosa import librosa filepath = "/Users/birenjianmo/Desktop/learn/librosa/mp3/in.wav" ...
- Python实现屏幕截图的两种方式
Python实现屏幕截图的两种方式 使用windows API 使用PIL中的ImageGrab模块 下面对两者的特点和用法进行详细解释. 一.Python调用windows API实现屏幕截图 好处 ...
- Python图片裁剪的两种方式——Pillow和OpenCV
本文参考Python图片裁剪的两种方式--Pillow和OpenCV并进行了一些更新 感谢作者:hfutdog 在这篇文章里我们聊一下Python实现图片裁剪的两种方式,一种利用了Pillow,还有一 ...
- python解释器在哪里_详解查看Python解释器路径的两种方式
进入python的安装目录, 查看python解释器 进入bin目录 # ls python(看一下是否有python解释器版本) # pwd (查看当前目录) 复制当前目录即可 1. 通过脚本查看 ...
- Qt实现多线程编程的两种方式
Qt实现多线程编程的两种方式 方式一: 继承自QThread类,覆写run函数.此实现方法只有run函数内的代码是运行在子线程内. 代码示例: #ifndef QDEMOTHREAD_H #defin ...
- 【Python】Python figure显示的两种方式
1. 两种方式: 终端输出图像 新窗口输出图像 2. 终端输出命令: %matplotlib inline 新窗口输出命令: %matplotlib qt5 注意此两个语句是命令行输入,若在spyde ...
- 多线程实现的两种方式及其区别
继承Thread public class Demo2_Thread {public static void main(String[] args) {MyThread mt = new MyThre ...
最新文章
- storm_常用命令
- 3、创建用户(3种方式)
- c语言的运算符表格,C语言教案(运算符和表格达式).ppt
- python中soup_python – 使用带有UTF-8的soup.get_text()
- Windows 11 预览版 Build 22000.120 发布
- [Nginx]nginx 配置实例-负载均衡
- 推荐算法的先验算法的连接_数据挖掘专注于先验算法
- 如何使用links方式安装Eclipse插件
- 递归不行就换动态规划(洛谷P1028题题解,Java语言描述)
- 紧张的飞秋(FEIQ)爱好者汗都下来了
- 老司机教你 5 分钟读懂 Python 装饰器
- IE10、IE11使用 __doPostBack 出现未定义问题
- python怎么复数乘方开方_孩子数学不好怎么办?怎样让孩子学好数学的方法
- beetl模板使用场景_Beetl使用指南
- 参加了一场温州游资的婚礼,也太壕了
- 怎么学计算机打字输入,电脑怎么学习打字
- java中测代码段运行时间及内存的方法
- 为什么用链路聚合_链路聚合技术作用和优点
- 【机器人学】冗余七自由度机械臂的解析解逆解算法
- 中国液晶玻璃市场现状调研与发展趋势预测报告2022-2028年