Python中的进程和线程
from multiprocessing import Process
process = Process(target=函数,name=进程的名字,args=(给函数传递的参数))
process.start() 启动进程并执行任务
process.run() 只是执行了任务但是没有启动进程
process.terminate() 终止进程
import threading
from multiprocessing import Process
from multiprocessing.pool import Pool
from multiprocessing.queues import Queue
from threading import Thread, Lock
from time import sleep
def task1(s):
while True:
print('这是任务1')
sleep(s)
def task2(s):
while True:
print('这是任务2')
sleep(s)
if __name__ == '__main__':
p1 = Process(target=task1, args=(1,))
p1.start()
p2 = Process(target=task2, args=(2,))
p2.start()
# 进程,线程
# Process类
# 创建进程
def func(n):
pass
p = Process(target=func, name='', args=(), kwargs='')
p.start()
# 自定义进程
class MyProcess(Process):
def run(self):
pass
p = MyProcess()
p.start()
# 进程数据共享:
n = 0
# 进程池:Pool
p = Pool(5)
# 阻塞式 apply(func,args,kwargs)
# 非阻塞式 apply_async(func,args,kwargs,callback=函数)
# 进程间通信
q = Queue(4)
q.put() # 放数据
q.get() # 取数据
q.qsize() # 获取队列中的数据个数
q.empty() # 判断队列是否为空
q.full() # 判断队列是否已经满了
# 线程
t = Thread(target=func, name='', args=(), kwargs='')
t.start()
# GIL:全局解释器锁
# Python中的线程是伪线程
# 线程同步
lock = Lock()
list1 = [0] * 10
def task1():
# 获取线程锁,如果已经上锁了,则等待锁的释放
lock.acquire() # 请求锁
for i in range(len(list1)):
list1[i] = 1
sleep(0.5)
lock.release() # 释放锁
def task2():
lock.acquire()
for i in range(len(list1)):
print('---->', list1[i])
sleep(0.5)
lock.release()
if __name__ == '__main__':
t1 = threading.Thread(target=task1)
t2 = threading.Thread(target=task2)
t2.start()
t1.start()
t2.join()
t1.join()
print(list1)
------学习贵在分享,贵在记录,贵在总结。