python -- 進程線程專題

來源:互聯網
上載者:User

標籤:pid   相關   get   包括   實現   python   輕鬆   star   很多   

要讓Python程式實現多進程(multiprocessing),我們先瞭解作業系統的相關知識。

Unix/Linux作業系統提供了一個fork()系統調用,它非常特殊。普通的函數調用,調用一次,返回一次,但是fork()調用一次,返回兩次,因為作業系統自動把當前進程(稱為父進程)複製了一份(稱為子進程),然後,分別在父進程和子進程內返回。

子進程永遠返回0,而父進程返回子進程的ID。這樣做的理由是,一個父進程可以fork出很多子進程,所以,父進程要記下每個子進程的ID,而子進程只需要調用getppid()就可以拿到父進程的ID。

Python的os模組封裝了常見的系統調用,其中就包括fork,可以在Python程式中輕鬆建立子進程:

import osprint('進程 id {} 開啟...'.format(os.getpid()))pid = os.fork() # 開啟新的進程,但仍是先有父進程if pid == 0:    print('我是子進程 id ({}) 被父進程 id ({}) 建立'.format(os.getpid(),os.getppid())) # 是被開啟的子進程else:    print('我是父進程 id ({}) 建立了子進程 id ({})'.format(os.getpid(),pid)) # 父進程 用來開啟別的進程import osprint("Process (%s) is start..." %os.getpid())pid = os.fork()print('pid: {}'.format(pid))if pid == 0:     print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))else:     print('I (%s) just created a child process (%s).' % (os.getpid(), pid))

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.