Python多線程編程簡(jiǎn)單介紹
創(chuàng)建線程
格式如下
threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
這個(gè)構(gòu)造器必須用關(guān)鍵字傳參調(diào)用
- group 線程組
- target 執(zhí)行方法
- name 線程名字
- args target執(zhí)行的元組參數(shù)
- kwargs target執(zhí)行的字典參數(shù)
Thread對(duì)象函數(shù)
函數(shù) 描述
start() 開(kāi)始線程的執(zhí)行
run() 定義線程的功能的函數(shù)(一般會(huì)被子類(lèi)重寫(xiě))
join(timeout=None) 程序掛起,直到線程結(jié)束;如果給了 timeout,則最多阻塞 timeout 秒
getName() 返回線程的名字
setName(name) 設(shè)置線程的名字
isAlive() 布爾標(biāo)志,表示這個(gè)線程是否還在運(yùn)行中
isDaemon() 返回線程的 daemon 標(biāo)志
setDaemon(daemonic) 把線程的 daemon 標(biāo)志設(shè)為 daemonic(一定要在調(diào)用 start()函數(shù)前調(diào)用)
常用示例
格式
import threading
def run(*arg, **karg):
pass
thread = threading.Thread(target = run, name = "default", args = (), kwargs = {})
thread.start()
實(shí)例
#!/usr/bin/python
#coding=utf-8
import threading
from time import ctime,sleep
def sing(*arg):
print "sing start: ", arg
sleep(1)
print "sing stop"
def dance(*arg):
print "dance start: ", arg
sleep(1)
print "dance stop"
threads = []
#創(chuàng)建線程對(duì)象
t1 = threading.Thread(target = sing, name = 'singThread', args = ('raise me up',))
threads.append(t1)
t2 = threading.Thread(target = dance, name = 'danceThread', args = ('Rup',))
threads.append(t2)
#開(kāi)始線程
t1.start()
t2.start()
#等待線程結(jié)束
for t in threads:
t.join()
print "game over"
輸出
sing start: ('raise me up',)
dance start: ('Rup',)
sing stop
dance stop
game over
相關(guān)文章
Python守護(hù)進(jìn)程用法實(shí)例分析
這篇文章主要介紹了Python守護(hù)進(jìn)程用法,實(shí)例分析了Python守護(hù)進(jìn)程的功能及使用方法,需要的朋友可以參考下2015-06-06如何使用Cython對(duì)python代碼進(jìn)行加密
這篇文章主要介紹了如何使用Cython對(duì)python代碼進(jìn)行加密,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-07-07Python Django中間件,中間件函數(shù),全局異常處理操作示例
這篇文章主要介紹了Python Django中間件,中間件函數(shù),全局異常處理操作,結(jié)合實(shí)例形式分析了Django中間件,中間件函數(shù),全局異常處理相關(guān)操作技巧,需要的朋友可以參考下2019-11-11Pandas中的loc與iloc區(qū)別與用法小結(jié)
loc函數(shù):通過(guò)行索引 “Index” 中的具體值來(lái)取行數(shù)據(jù)(如取"Index"為"A"的行)而iloc函數(shù):通過(guò)行號(hào)來(lái)取行數(shù)據(jù)(如取第二行的數(shù)據(jù)),這篇文章介紹Pandas中的loc與iloc區(qū)別與用法,感興趣的朋友一起看看吧2024-01-01淺談Python中進(jìn)程的創(chuàng)建與結(jié)束
這篇文章主要介紹了淺談Python中進(jìn)程的創(chuàng)建與結(jié)束,但凡是硬件,都需要有操作系統(tǒng)去管理,只要有操作系統(tǒng),就有進(jìn)程的概念,就需要有創(chuàng)建進(jìn)程的方式,需要的朋友可以參考下2023-07-07python中根據(jù)字符串調(diào)用函數(shù)的實(shí)現(xiàn)方法
下面小編就為大家?guī)?lái)一篇python中根據(jù)字符串調(diào)用函數(shù)的實(shí)現(xiàn)方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧2016-06-06