python: 多线程实现的两种方式及让多条命令并发执行
生活随笔
收集整理的這篇文章主要介紹了
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: 多线程实现的两种方式及让多条命令并发执行的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《Zabbix安装部署-1》-Cento
- 下一篇: Tesseract-OCR 训练过程 V