1. 程式人生 > >線程與進程概述

線程與進程概述

並發 很大的 多線程 thread art pytho all reading python3

進程和線程簡單而基本靠譜的定義如下:
1. 進程:程序的一次執行
2. 線程:CPU的基本調度單位

單線程實例:

#!/usr/bin/python3 
from time import ctime, sleep
#說 def talk():
  print(‘Start talk: %r‘%ctime())
  sleep(2)
#寫 def write():
  print(‘Start write: %r‘%ctime())
  sleep(3)
if __name__ == ‘__main__‘:
  talk()
  write()
  print(‘All end %r‘%ctime())

執行結果:
Start talk: ‘Sat Feb 10 17:27:45 2018‘
Start write: ‘Sat Feb 10 17:27:47 2018‘
All end ‘Sat Feb 10 17:27:50 2018‘
單線程在程序執行時,所走的程序路徑按照連續順序排下來,前面的必須處理好,後面的才會執行。


多線程:
多線程(MultiThreading)是指從軟件或者硬件上實現多個線程並發執行的技術。
案例:讓學生同時進行說和寫操作
#!/usr/bin/python3  
from time import sleep, ctime
import threading
#定義說和寫的方法
def talk(content,loop):
  for i in range(loop):
  print(‘Start talk: %s %s‘%(content,ctime()))
  sleep(2)

def write(content,loop):
  for i in range(loop):
    print(‘Start write: %s %s‘%(content,ctime()))
    sleep(3)
#定義和加載說和寫的線程
threads = [] t1 =threading.Thread(target=talk, args=(‘Hello 51zxw!‘, 2))
threads.append(t1)
t2 = threading.Thread(target=write,args=(‘Life is short you need python‘, 2))
threads.append(t2)
#執行多線程
if __name__ == ‘__main__‘:
  for t in threads:
    t.start()
  for t in threads:
    t.join()
  print(‘All Thread end! %s‘%ctime())
執行結果:
Start talk: Hello 51zxw! Sat Feb 10 17:56:03 2018
Start write: Life is short you need python Sat Feb 10 17:56:03 2018
Start talk: Hello 51zxw! Sat Feb 10 17:56:05 2018
Start write: Life is short you need python Sat Feb 10 17:56:06 2018
All Thread end! Sat Feb 10 17:56:09 2018



多線程
from time import ctime, sleep 
import multiprocessing
#定義兩個方法說和寫
def talk(content,loop):
  for i in range(loop):
    print(‘Talk: %s %s‘%(content,ctime()))
    sleep(2)


def write(content,loop):
  for i in range(loop):
    print(‘Write: %s %s‘%(content,ctime()))
    sleep(3)
#定義兩個進程
process = []
p1 = multiprocessing.Process(target=talk, args = (‘Hello 51zxw‘, 2))
process.append(p1)
p2 = multiprocessing.Process(target=write, args=(‘Python‘, 2))
process.append(p2)
#調用進程
if __name__ == ‘__main__‘:
  for p in process:
    p.start()
  for p in process:
    p.join()
  print(‘All end %s‘%ctime())

執行結果:
Talk: Hello 51zxw Sat Feb 10 18:23:46 2018
Write: Python Sat Feb 10 18:23:46 2018
Talk: Hello 51zxw Sat Feb 10 18:23:48 2018
Write: Python Sat Feb 10 18:23:49 2018
All end Sat Feb 10 18:23:52 2018

從結果分析,多進程與多線程的執行結果相似,但實現的過程卻有很大的不同,不同之處還需深入了解。
 




線程與進程概述