python多线程-多进程

多线程

  • 线程的创建
from threading import Thread
import os
t = Thread(target=os.getcwd,name='thread_1')
t.start()
  • 多线程的创建
from threading import Thread
import os


if __name__ == "__main__":
    threads_list = []
    for i in range(5):
        t = Thread(target=print,args=(i,))
        threads_list.append(t)
        t.start()
    
    for t in threads_list:
        t.join()

互斥锁Lock

  • 使用的时候和进程通信的Queue对象一样使用
from threading import Thread,Lock
import os
import time
def func(lock,i):  # type:Lock
    lock.acquire()
    time.sleep(0.5)
    print(f'this is func{i}')

    lock.release()



if __name__ == "__main__":
    l = Lock()
    threads_list = []
    for i in range(5):
        # t = Thread(target=print,args=(i,))
        t = Thread(target=func,args=(l,i))   
        threads_list.append(t)
        t.start()
    
    for t in threads_list:
        t.join()
>>>
this is func0	每隔约0.5秒打印一次
this is func1
this is func2
this is func3
this is func4

信号量Semaphore

  • 实现的的是锁的功能,但是和进程池有些类似,一共就n个资源,谁来了谁拿,不够了排队等着
from threading import Thread,Lock,Semaphore
import os
import time
def func(semaphore,i):  # type:Lock
    with semaphore:
    	time.sleep(0.5)
	    print(f'this is func{i}')


if __name__ == "__main__":
    s = Semaphore(5)
    threads_list = []
    for i in range(5):
        # t = Thread(target=print,args=(i,))
        t = Thread(target=func,args=(s,i))   
        threads_list.append(t)
        t.start()
    
    for t in threads_list:
        t.join()

事件

  • 事件中常用的方法:event.set(),event.clear(),event.is_set() ,event.wait()
from threading import Thread,Lock,Event
import os
import time
def func(event):  # type:Event
    print(f'this is func')
    time.sleep(1)
    event.set()
def func2(event):  # type:Event
    while True:
        event.wait()
        print('this is func2')
        time.sleep(.5)

if __name__ == "__main__":
    event = Event()
    threads_list = []

    t1 = Thread(target=func,args=(event,))   
    t2 = Thread(target=func2,args=(event,))   
    t1.start()
    t2.start()
    t1.join()
    t2.join()

多进程

进程通信

  1. socket套接字:发送方和接收方都是本机即可实现进程的通信
  2. 进程Queue,通过putput_nowait(),get(),get_nowait(),其中**_nowait()方法会异常,另两个方法会阻塞。
  3. 管道Pipe,创建一个管道得到两个对象,其中一个传给子进程,使用send()方法和recv()方法实现进程通信
  4. 使用共享内存Array,Value
  5. 使用管理器Manager:支持list,dict, Namespace 、 Lock 、 RLock 、 Semaphore 、 BoundedSemaphore 、 Condition 、 Event 、 Barrier 、 Queue 、 Value 和 Array
def f(l):
    l.append(999)
if __name__ == '__main__':
    
    with Manager() as manager:
        l = manager.list(range(10))

        p = Process(target=f,args=(l,))
        p.start()
        p.join()
        print(l)

进程池

  • 多开线程的开销是小的,但是进程的创建会很慢,所以需要进程复用
import os
def func(i):
	print(f'{i}:{os.getpid()}')
	
if __name__ == '__main__'
	pool = Pool(5) #默认是cpu数 
	
	for i in range(100):
		pool.apply_async(target=func,args=(i,))
	pool.close()
	pool.start()
	# 也可以 with Pool(5) as pool:上下文会更方便

你可能感兴趣的:(随笔)