線程和進程

操做系統/應用程序python

硬件,硬盤、cpu、主板、顯卡、內存、電源... ...linux

裝系統(軟件)程序員

系統就是由一個程序員寫出來軟件,該關鍵用於控制計算機的硬件,讓他們之間進行相互配合windows

軟件安裝(安裝應用程序)安全

qq  360  百度雲   pycharm多線程

併發和並行併發

併發,僞,因爲執行速度特別快,人感受不到停頓。app

並行,真,建立10我的同時操做。ide

進程和線程函數

單進程、單線程的應用程序

print("666")

  到底什麼是線程?什麼是進程?

Python本身沒有這玩意,Python中調用的操做系統的線程和進程。

單線程、多線程的應用程序

import threading
print("666")

def func(arg):
      print(arg)
t = threading.Thread(target=func)
t.start()

print("end")

 python線程編寫

import threading
v1 = [11,22,33]
v2 = [44,55,66]

def func(data,plus):
     for i in range(len(data)):
          data[i] = data[i] + plus

t1 = threading.Thread(target=func,args=(v1,1))
t1.start()

t2 = threading.Thread(target=func,args=(v2,100))
t2.start()

python鎖

python的GIL鎖

python內置一個全局解釋器鎖,鎖的做用就是保證同一時刻一個進程中只有一個線程能夠被cpu調用

線程鎖:因爲線程之間是進行隨機調度,而且每一個線程可能只執行n條執行以後,當多個線程同時修改同一條數據時可能會出現髒數據,因此,出現了線程鎖 - 同一時刻容許一個線程執行操做。

 lock/Rlock   一次放1個

import threading
import time

v = []
lock = threading.Lock()

def func(arg):
    lock.acquire()
    v.append(arg)
    time.sleep(0.01)
    m = v[-1]
    print(arg,m)
    lock.release()


for i in range(10):
    t =threading.Thread(target=func,args=(i,))
    t.start()


v = []
lock = threading.RLock()
def func(arg):
    lock.acquire()
    lock.acquire()

    v.append(arg)
    time.sleep(0.01)
    m = v[-1]
    print(arg,m)

    lock.release()
    lock.release()


for i in range(10):
    t =threading.Thread(target=func,args=(i,))
    t.start()

  BoundedSemaphore(1次放N個)信號量

import time
import threading

lock = threading.BoundedSemaphore(3)
def func(arg):
    lock.acquire()
    print(arg)
    time.sleep(1)
    lock.release()


for i in range(20):
    t =threading.Thread(target=func,args=(i,))
    t.start()

  condition鎖,一次放n個

import time
import threading

lock = threading.Condition()

# ############## 方式一 ##############

def func(arg):
    print('線程進來了')
    lock.acquire()
    lock.wait() # 加鎖

    print(arg)
    time.sleep(1)

    lock.release()


for i in range(10):
    t =threading.Thread(target=func,args=(i,))
    t.start()

while True:
    inp = int(input('>>>'))

    lock.acquire()
    lock.notify(inp)
    lock.release()


# ############## 方式二 ##############
"""
def xxxx():
    print('來執行函數了')
    input(">>>")
    # ct = threading.current_thread() # 獲取當前線程
    # ct.getName()
    return True

def func(arg):
    print('線程進來了')
    lock.wait_for(xxxx)
    print(arg)
    time.sleep(1)

for i in range(10):
    t =threading.Thread(target=func,args=(i,))
    t.start()

"""

 鎖Event    一次所有放  

import time
import threading

lock = threading.Event()


def func(arg):
    print('線程來了')
    lock.wait() # 加鎖:紅燈
    print(arg)


for i in range(10):
    t =threading.Thread(target=func,args=(i,))
    t.start()

input(">>>>")
lock.set() # 綠燈


lock.clear() # 再次變紅燈

for i in range(10):
    t =threading.Thread(target=func,args=(i,))
    t.start()

input(">>>>")
lock.set()

 

 爲何要加鎖:

非線程安全

控制一段代碼

threading.local

做用:內部自動爲每一個線程維護一個空間(字典),用於當前存取屬於本身的值。保證線程之間的數據隔離。

 示例:

import time
import threading

v = threading.local()
def func(arg):
    # 內部會爲當前線程建立一個空間用於存儲:phone=本身的值
    v.phone = arg
    time.sleep(2)
    print(v.phone,arg) # 去當前線程本身空間取值

for i in range(10):
    t =threading.Thread(target=func,args=(i,))
    t.start()

  線程池

生產者消費者模型

三部件:

生產者

隊列,先進先出

擴展:棧,後進先出

消費者

問:生產者消費者模型解決了什麼問題?

不用一直等待的問題。

import time
import queue
import threading
q = queue.Queue() # 線程安全

def producer(id):
    """
    生產者
    :return:
    """
    while True:
        time.sleep(2)
        q.put('包子')
        print('廚師%s 生產了一個包子' %id )

    for i in range(1,4):
        t = threading.Thread(target=producer,args=(i,))
        t.start()


    def consumer(id):
    """
    消費者
    :return:
    """
    while True:
        time.sleep(1)
        v1 = q.get()
        print('顧客 %s 吃了一個包子' % id)

    for i in range(1,3):
	t = threading.Thread(target=consumer,args=(i,))
	t.start()                

 

進程 :

進程間數據不共享

data_list = []

def task(arg):
    data_list.append(arg)
    print(data_list)


def run():
    for i in range(10):
        p = multiprocessing.Process(target=task,args=(i,))
        # p = threading.Thread(target=task,args=(i,))
        p.start()

if __name__ == '__main__':
    run()

 經常使用功能:

join、deamon、name、multiprocessing.current_process()、multiprocessing.current_process().ident/pid

 類繼承方式建立進程:

import multiprocessing
class MyProcess(multiprocessing.Process):

    def run(self):
        print('當前進程',multiprocessing.current_process())


def run():
    p1 = MyProcess()
    p1.start()

    p2 = MyProcess()
    p2.start()

if __name__ == '__main__':
    run()

  進程間數據共享:

 

Queue:
linux:
	q = multiprocessing.Queue()

	def task(arg,q):
		q.put(arg)

	def run():
		for i in range(10):
			p = multiprocessing.Process(target=task, args=(i, q,))
			p.start()

		while True:
			v = q.get()
			print(v)

	run()
windows:	
def task(arg,q):
	q.put(arg)

if __name__ == '__main__':
	q = multiprocessing.Queue()
	for i in range(10):
		p = multiprocessing.Process(target=task,args=(i,q,))
		p.start()
	while True:
		v = q.get()
		print(v)
	
Manager:(*)
Linux:
	m = multiprocessing.Manager()
	dic = m.dict()

	def task(arg):
		dic[arg] = 100

	def run():
		for i in range(10):
			p = multiprocessing.Process(target=task, args=(i,))
			p.start()

		input('>>>')
		print(dic.values())
		
	if __name__ == '__main__':
		
		run()
windows:
	def task(arg,dic):
		time.sleep(2)
		dic[arg] = 100

	if __name__ == '__main__':
		m = multiprocessing.Manager()
		dic = m.dict()

		process_list = []
		for i in range(10):
			p = multiprocessing.Process(target=task, args=(i,dic,))
			p.start()

			process_list.append(p)

		while True:
			count = 0
			for p in process_list:
				if not p.is_alive():
					count += 1
			if count == len(process_list):
				break
		print(dic)

 

 進程鎖

import time
import threading
import multiprocessing


lock = multiprocessing.RLock()

def task(arg):
    print('鬼子來了')
    lock.acquire()
    time.sleep(2)
    print(arg)
    lock.release()


if __name__ == '__main__':
    p1 = multiprocessing.Process(target=task,args=(1,))
    p1.start()

    p2 = multiprocessing.Process(target=task, args=(2,))
    p2.start()

  爲何要加鎖??

進程池

import time
from concurrent.futures import ThreadPoolExecutor,ProcessPoolExecutor

def task(arg):
    time.sleep(2)
    print(arg)

if __name__ == '__main__':

    pool = ProcessPoolExecutor(5)
    for i in range(10):
        pool.submit(task,i)
相關文章
相關標籤/搜索
本站公眾號
   歡迎關注本站公眾號,獲取更多信息