Python 線程與進程

來源:互聯網
上載者:User

標籤:最小   on()   list   解譯器   子線程   target   多個   run   get   

線程是作業系統能夠進行運算調度的最小單位。它被包含在進程之中,是進程中的實際運作單位。一條線程指的是進程中一個單一順序的控制流程,一個進程中可以並發多個線程,每條線程並存執行不同的任務。

使用 threading 模組

方法一:

import threadingimport timedef foo(n):    print(‘foo %s‘%n)    time.sleep(1)    print(‘end foo‘)def bar(n):    print(‘bar %s‘%n)    time.sleep(2)    print(‘end bar‘)t1 = threading.Thread(target=foo, args=(1,))t2 = threading.Thread(target=bar, args=(2,))t1.start()t2.start()print(‘........in the main..........‘)運行結果:foo 1bar 2........in the main..........end fooend bar

方法二:

import time, threadingclass MyThread(threading.Thread):    def __init__(self, num):        threading.Thread.__init__(self)        self.num = num    def run(self):             #定義線程要啟動並執行函數        print("running on number:%s" % self.num)        time.sleep(3)if __name__ == ‘__main__‘:    t1 = MyThread(1)    t2 = MyThread(2)    t1.start()    t2.start()運行結果:running on number:1running on number:2
join 方法使得主線程等待子線程完成才繼續
import threadingimport timebegin = time.time()def foo(n):    print(‘foo %s‘%n)    time.sleep(1)    print(‘end foo‘)def bar(n):    print(‘bar %s‘%n)    time.sleep(2)    print(‘end bar‘)t1 = threading.Thread(target=foo, args=(1,))t2 = threading.Thread(target=bar, args=(2,))t1.start()t2.start()t1.join()t2.join()print(‘........in the main..........‘)運行結果:foo 1bar 2end fooend bar........in the main..........
在計算密集型任務中串列與多線程進行對比
import threading, timebegin = time.time()def add(n):    sum = 0    for i in range(n):        sum += i    print(sum)add(100000000)add(200000000)end = time.time()print(end-begin)運行結果:49999999500000001999999990000000017.66856598854065import threading, timebegin = time.time()def add(n):    sum = 0    for i in range(n):        sum += i    print(sum)t1 = threading.Thread(target=add, args=(100000000,))t1.start()t2 = threading.Thread(target=add, args=(200000000,))t2.start()t1.join()t2.join()end = time.time()print(end-begin)運行結果:49999999500000001999999990000000021.088160276412964# 結果為串列運行比多線程運行更快
Cpython 中有 GIL (Global Interpreter Lock,全域解譯器鎖),所以在同一時刻,只能有一個線程進入調度。如果任務是IO密集型的,可以使用多線程;如果任務是計算密集型的,最優方法是改成 C。setDaemon()

調用該方法只要是主線程完成,不管子線程是否完成都要和主線程一起退出。

threading.currentThread()

返回當前的線程變數。

threading.active_count()

返回正在啟動並執行線程數量。

import threading, timefrom time import ctime,sleepdef music(func):    print(threading.current_thread())    for i in range(2):        print("Begin listening to %s. %s" %(func, ctime()))        sleep(2)        print("end listening %s" %ctime())def movie(func):    print(threading.current_thread())    for i in range(2):        print("Begin watching at the %s %s" %{func, ctime()})        sleep(4)        print("end watching %s" %ctime())threads = []t1 = threading.Thread(target=music, args=(‘klvchen‘,))threads.append(t1)t2 = threading.Thread(target=movie, args=(‘lili‘,))threads.append(t2)if __name__ == ‘__main__‘:    for t in threads:        t.setDaemon(True)        t.start()    print(threading.current_thread())    print(threading.active_count())    print("all over %s" %ctime())運行結果:<Thread(Thread-1, started daemon 5856)>Begin listening to klvchen. Wed Jul 11 23:43:51 2018<Thread(Thread-2, started daemon 9124)><_MainThread(MainThread, started 9444)>3all over Wed Jul 11 23:43:51 2018

Python 線程與進程

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.