python:線程,python線程

來源:互聯網
上載者:User

python:線程,python線程
線程

1,線程與進程

進程:執行中的程式。進程可以處理一個任務。對於一個人來說一個人就是一個進程。進程被包含著線程。

線程:輕量級的進程。一個時間點只做一件事。一個人可以做的多件事情,每一件事情都是一個線程。

2,線程是CPU調度的最小單位。進程是資源分派的最小單位

3,開啟線程的時空開銷 都比 開啟進程要小,且cpu線上程之間切換比在進程之間切換快。

4,一個程式中 可以同時有多進程和線程

1)調用模組開啟線程

import osimport timefrom threading import Threaddef func():    # 子線程    time.sleep(1)    print('hello world',os.getpid())thread_lst = []for i in range(10):    t = Thread(target=func)    t.start()    thread_lst.append(t)[t.join() for t in thread_lst]print(os.getpid())   # 主線程

2)調用類開啟線程

import osimport timefrom threading import Threadclass MyThread(Thread):    count = 0         # 靜態屬性    def __init__(self,arg1,arg2):        super().__init__()        self.arg1 = arg1        self.arg2 = arg2    def run(self):        MyThread.count += 1        time.sleep(1)        print('%s,%s,%s,%s'%(self.arg1,self.arg2,self.name,os.getpid()))for i in range(10):    t = MyThread(i,i*'*')    t.start()print(t.count)

 

聯繫我們

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