1. 程式人生 > 實用技巧 >python之執行緒與程序

python之執行緒與程序

多工的實現有3種方式:

  • 多程序模式;
  • 多執行緒模式;
  • 多程序+多執行緒模式。

多程序

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

multiprocessing模組就是跨平臺版本的多程序模組

# from multiprocessing import Process
# import os
# def run_proc(name):
#     print('Run child process %s (%s)...' % (name, os.getpid()))#用.getpid()就可以拿到父程序的ID
# if __name__=='__main__':#生成程序必須要有 # print('Parent process %s.' % os.getpid())#用.getpid()就可以拿到子程序的ID # p = Process(target=run_proc, args=('ww',)) #生成一個程序 target=run_proc呼叫函式, args=('test',)為函式新增引數 # print('Child process will start.') # p.start()#開始執行子程序 # p.join()#等待子程序執行結束 # print('Child process end.')

Pool

如果要啟動大量的子程序,可以用程序池的方式批量建立子程序

# from multiprocessing import Pool
# import os, time, random
# def long_time_task(name):
#     print('Run task %s (%s)...' % (name, os.getpid()))#用.getpid()就可以拿到父程序的ID
#     start = time.time()#程序開始時間
#     time.sleep(random.random() * 3)#休眠(隨機數*3)秒
#     end = time.time()#程序結束時間
# print('Task %s runs %0.2f seconds.' % (name, (end - start))) # if __name__=='__main__': # print('Parent process %s.' % os.getpid()) # p = Pool(4)#允許同時執行的程序 # for i in range(5): # p.apply_async(long_time_task, args=(i,))#生成程序 # print('Waiting for all subprocesses done...') # p.close()#開始執行子程序 # p.join()#等待執行的子程序結束 # print('All subprocesses done.')

多執行緒

程序是由若干執行緒組成的,一個程序至少有一個執行緒。

Python的執行緒是真正的Posix Thread,而不是模擬出來的執行緒。

# import time, threading
# # 新執行緒執行的程式碼:
# def loop():
#     print('thread %s is running...' % threading.current_thread().name)#threading模組有個current_thread(),永遠返回當前執行緒的例項,主執行緒例項的名字叫MainThread
#     n = 0
#     while n < 5:
#         n = n + 1
#         print('thread %s >>> %s' % (threading.current_thread().name, n))
#         time.sleep(1)#使執行緒休眠1秒
#     print('thread %s ended.' % threading.current_thread().name)
# print('thread %s is running...' % threading.current_thread().name)
# t = threading.Thread(target=loop, name='LoopThread')#生成一個執行緒
# t.start()#開始子執行緒
# t.join()#等待子執行緒結束
# print('thread %s ended.' % threading.current_thread().name)