python实现多线程的方式及多条命令并发执行

yipeiwu_com6年前Python基础

一、概念介绍

Thread 是threading模块中最重要的类之一,可以使用它来创建线程。有两种方式来创建线程:一种是通过继承Thread类,重写它的run方法;另一种是创建一个threading.Thread对象,在它的初始化函数(__init__)中将可调用对象作为参数传入.
Thread模块是比较底层的模块,Threading模块是对Thread做了一些包装的,可以更加方便的被使用。
另外在工作时,有时需要让多条命令并发的执行, 而不是顺序执行。

二、代码样例

#!/usr/bin/python
# encoding=utf-8
# Filename: thread-extends-class.py
# 直接从Thread继承,创建一个新的class,把线程执行的代码放到这个新的 class里
import threading
import time
 
class ThreadImpl(threading.Thread):
 def __init__(self, num):
  threading.Thread.__init__(self)
  self._num = num
 
 def 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, mutex
 total = 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 time
 
def 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, mutex
 total = 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 total
 
 
if __name__ == '__main__':
 # 创建40个线程
 main(40)
#!/usr/bin/python
# encoding=utf-8
# Filename: put_files_hdfs.py
# 让多条命令并发执行,如让多条scp,ftp,hdfs上传命令并发执行,提高程序运行效率
import datetime
import os
import threading

def 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 django搭建layui提交表单,表格,图标的实例

Python django搭建layui提交表单,表格,图标的实例

利用layui制作与众不同的感谢表单,表格 layui极大的提高了前端开发效率,它极具个性的样式等等都非常吸引人,接下来我将为大家展示如何利用Python的django框架与layui制...

python for循环remove同一个list过程解析

下午在用python将Linux的conf配置文件转化成字典dict时遇到了一个奇怪的问题,原先conf配置文件中没有注释行(以#开头的行),后来为了避免这种情况,添加了一个对以#开头的...

python smtplib模块自动收发邮件功能(二)

python smtplib模块自动收发邮件功能(二)

接上篇python smtplib模块自动收发邮件功能(一) ,用python smtplib模块实现了发送邮件程序了,那么接下来我们需要现在要解决的问题如何在 test_report\...

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

Python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围

一、用默认设置绘制折线图 import matplotlib.pyplot as plt x_values=list(range(11)) #x轴的数字是0到10这11个整数 y...

python框架中flask知识点总结

有很久没有更新我的博客了,在学习flask去了,别人都说flask不难,其实现在我也这么觉得,但是在刚接触的时候还是有点吃力的。 在学习的过程中查阅了不少,也了解了许多,今天想做个总结。...