python多線程操作執行個體

來源:互聯網
上載者:User
一、python多線程

因為CPython的實現使用了Global Interpereter Lock(GIL),使得python中同一時刻只有一個線程在執行,從而簡化了python解譯器的實現,且python物件模型天然地安全執行緒。如果你想你的應用程式在多核的機器上使用更好的資源,建議使用multiprocessing或concurrent.futures.processpoolexecutor。但是如果你的程式是IO密集型,則使用線程仍然是很好的選擇。

二、python多線程使用的兩種方法

執行個體:

複製代碼 代碼如下:


import threading
import time

def worker(num):
print (threading.currentThread().getName() + ' start')
time.sleep(10)
print (threading.currentThread().getName() + ' running')
print (threading.currentThread().getName() + " " + str(num))
print (threading.currentThread().getName() + ' exit')

def deamon():
print (threading.currentThread().getName() + ' start')
time.sleep(20)
print (threading.currentThread().getName() + ' running')
print (threading.currentThread().getName() + ' exit')

print(threading.currentThread().getName())

d = threading.Thread(name='deamon', target=deamon)
d.setDaemon(True)
d.start()

w = threading.Thread(name='worker', target=worker, args=(10,))
w.start()

class myWorker(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
self.thread_stop = False

def run(self):
print (self.getName()+' start')
time.sleep(30)
print (self.getName()+' running')
print (self.getName()+" " + str(self.num))
print (self.getName()+' exit')

mw = myWorker(30)
mw.setName("MyWorker")
mw.start()

print(threading.currentThread().getName())

print("All threads:")
print("------------")
for th in threading.enumerate():
print(th.getName())
print("------------")

d.join()
w.join()
mw.join()

print(threading.currentThread().getName())

運行結果如下:

1)python線程使用的兩種方法:

**直接調用threading.Thread來構造thread對象,Thread的參數如下:
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
group為None;
target為線程將要執行的功能函數;
name為線程的名字,也可以在物件建構後調用setName()來設定;
args為tuple類型的參數,可以為多個,如果只有一個也的使用tuple的形式傳入,例如(1,);
kwargs為dict類型的參數,也即位具名引數;

**實現自己的threading.Thread的子類,需要重載__init__()和run()。

2)threading.Thread對象的其他方法:

start(),用來啟動線程;
join(), 等待直到線程結束;
setDeamon(), 設定線程為deamon線程,必須在start()調用前調用,預設為非demon。
注意: python的主線程在沒有非deamon線程存在時就會退出。

3)threading的靜態方法:

threading.current_thread() , 用來獲得當前的線程;
threading.enumerate() , 用來多的當前存活的所有線程;
threading.Timer 定時器,其實是thread的一個字類型,使用如下:
複製代碼 代碼如下:


def hello(): print("hello, world")
t = Timer(30.0, hello)
t.start()

4)logging是安全執行緒的

logging 模組是安全執行緒的,所以可以使用logging來協助調試多線程程式。
複製代碼 代碼如下:


import logging
logging.basicConfig(level=logging.DEBUG,
format="(%(threadName)-10s : %(message)s",
)
logging.debug("wait_for_event_timeout starting")
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.