談談對線程與進程的理解


概念:

線程

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

進程

進程(Process)是計算機中的程序關於某數據集合上的一次運行活動,是系統進行資源分配和調度的基本單位,是操作系統結構的基礎。在早期面向進程設計的計算機結構中,進程是程序的基本執行實體;在當代面向線程設計的計算機結構中,進程是線程的容器。程序是指令、數據及其組織形式的描述,進程是程序的實體。

進程與線程區別

a.地址空間和其它資源:進程間相互獨立,同一進程的各線程間共享。某進程內的線程在其它進程不可見。

b.通信:進程間通信IPC,線程間可以直接讀寫進程數據段(如全局變量)來進行通信——需要進程同步和互斥手段的輔助,以保證數據的一致性。

c.調度和切換:線程上下文切換比進程上下文切換要快得多。

d.在多線程OS中,進程不是一個可執行的實體。

 

threading模塊

直接調用

 1 import threading
 2 import time
 3 
 4 def tell(num): #定義每個線程要運行的函數
 5 
 6     print(num)
 7     time.sleep(3)
 8 
 9 if __name__ == '__main__':
10     t1 = threading.Thread(target=tell,args=(1,)) #生成一個線程實例
11     t2 = threading.Thread(target=tell,args=(2,)) #生成另一個線程實例
12     t1.start() #啟動線程
13     t2.start() #啟動另一個線程
14     print(t1.getName()) #獲取線程名
15     print(t2.getName())
View Code

繼承調用

 1 __author__ = 'thinkpad'
 2 # !/usr/bin/env python
 3 #-*- coding:utf-8 -*-
 4 
 5 import threading
 6 import time
 7 
 8 class MyThread(threading.Thread):
 9 
10     def __init__(self,num):
11         threading.Thread.__init__(self)
12         self.num = num
13     def run(self):#定義每個線程要運行的函數
14         print(self.num)
15         time.sleep(3)
16 
17 if __name__ == '__main__':
18     t1 = MyThread(1)
19     t2 = MyThread(2)
20     t1.start()
21     t2.start()
22     print(t1.getName())
23     print(t2.getName())
View Code

 互拆鎖

 1 __author__ = 'thinkpad'
 2 # !/usr/bin/env python
 3 #-*- coding:utf-8 -*-
 4 import threading
 5 import time
 6 
 7 def addNum():
 8     global num #在每個線程中都獲取這個全局變量
 9     print('--get num:',num )
10     time.sleep(1)
11     lock.acquire() #修改數據前加鎖
12     num  -=1 #對此公共變量進行-1操作
13     lock.release() #修改后釋放
14 num = 100  #設定一個共享變量
15 thread_list = []
16 
17 lock = threading.Lock() #生成全局鎖
18 for i in range(100):
19     t = threading.Thread(target=addNum)
20     t.start()
21     thread_list.append(t)
22 
23 for t in thread_list: #等待所有線程執行完畢
24     t.join()
25 print('final num:', num )
View Code

 

多進程Mutiprocessing

 1 from multiprocessing import Process
 2 import time
 3 def f(name):
 4     time.sleep(2)
 5     print('hello', name)
 6 
 7 if __name__ == '__main__':
 8     for i in range(4):
 9         p = Process(target=f, args=('bob',))
10         p.start()
11         p.join()
View Code
 1 from multiprocessing import Process
 2 import os
 3 
 4 def info(title):
 5     print(title)
 6     print('module name:', __name__)
 7     print('parent process:', os.getppid())
 8     print('process id:', os.getpid())
 9     print("\n\n")
10 
11 def f(name):
12     info('\033[31;1mfunction f\033[0m')
13     print('hello', name)
14 
15 if __name__ == '__main__':
16     info('\033[32;1mmain process line\033[0m')
17     p = Process(target=f, args=('bob',))
18     p.start()
19     p.join()
View Code

 

 進程間通訊

queues

 1 from multiprocessing import Process, Queue
 2  
 3 def f(q):
 4     q.put([42, None, 'hello'])
 5  
 6 if __name__ == '__main__':
 7     q = Queue()
 8     p = Process(target=f, args=(q,))
 9     p.start()
10     print(q.get())    # prints "[42, None, 'hello']"
11     p.join()
View Code

Pipes

 1 from multiprocessing import Process, Pipe
 2 
 3 def f(conn):
 4     conn.send([42, None, 'hello'])
 5     conn.close()
 6  
 7 if __name__ == '__main__':
 8     parent_conn, child_conn = Pipe()
 9     p = Process(target=f, args=(child_conn,))
10     p.start()
11     print(parent_conn.recv())   # prints "[42, None, 'hello']"
12     p.join()
View Code

Mangager

 1 from multiprocessing import Process, Manager
 2 
 3 def f(d, l):
 4     d[1] = '1'
 5     d[2] = '2'
 6     d[0.25] = None
 7     l.append(1)
 8     print(l)
 9 
10 if __name__ == '__main__':
11     with Manager() as manager:
12         d = manager.dict()
13 
14         l = manager.list(range(5))
15         p_list = []
16         for i in range(10):
17             p = Process(target=f, args=(d, l))
18             p.start()
19             p_list.append(p)
20         for res in p_list:
21             res.join()
22 
23         print(d)
24         print(l)
View Code

進程同步

 1 from multiprocessing import Process, Lock
 2  
 3 def f(l, i):
 4     l.acquire()
 5     try:
 6         print('hello world', i)
 7     finally:
 8         l.release()
 9  
10 if __name__ == '__main__':
11     lock = Lock()
12  
13     for num in range(10):
14         Process(target=f, args=(lock, num)).start()
View Code

進程池

 1 from  multiprocessing import Process,Pool
 2 import time
 3 
 4 def Foo(i):
 5     time.sleep(2)
 6     return i+100
 7 
 8 def Bar(arg):
 9     print('-->exec done:',arg)
10 
11 pool = Pool(5)
12 
13 for i in range(10):
14     pool.apply_async(func=Foo, args=(i,),callback=Bar)
15     #pool.apply(func=Foo, args=(i,))
16 
17 print('end')
18 pool.close()
19 pool.join()#進程池中進程執行完畢后再關閉,如果注釋,那么程序直接關閉。
View Code

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM