1、 通过进程和queue实现简单的生产者消费者默写
import time
import random
from multiprocessing import Process, Queue, JoinableQueue
def producer(name, food, q):
for i in range(10):
data = '%s 制造了%s' % (name, food)
time.sleep(random.randint(1, 3))
print(data)
q.put(food)
def consumer(name, q):
while True:
food = q.get()
time.sleep(random.randint(1, 3))
print('%s消费了%s' % (name, food))
q.task_done()
if __name__ == '__main__':
q = JoinableQueue()
p = Process(target=producer, args=('egon', '包子', q))
p.start()
p1 = Process(target=producer, args=('alex', '泔水', q))
p1.start()
c = Process(target=consumer, args=('鸡哥', q))
c.start()
c1 = Process(target=consumer, args=('王铁蛋', q))
c1.start()
c2 = Process(target=consumer, args=('李铁柱', q))
c2.start()
p.join()
p1.join()
q.join()
print('生产者结束了,主进程结束')
2、 代码实现开启线程两种方式
from threading import Thread, Lock
import time
import json
import random
class Task(Thread):
def __init__(self, n):
super().__init__()
self.n = n
def run(self) -> None:
print(f'我是子线程{self.n}')
if __name__ == '__main__':
a = Task('一号')
a.start()
def task(n):
print(f'我是子进程{n}')
if __name__ == '__main__':
a = Thread(target=task, args=('一号',))
a.start()
3、 代码实现等待子线程执行完成,主线程再继续执行
def task(n, y):
time.sleep(y)
print(f'我是子进程{n}')
if __name__ == '__main__':
a = Thread(target=task, args=('一号', 2))
a1 = Thread(target=task, args=('2号', 4))
a.start()
a1.start()
a.join()
a1.join()
print('主进程完毕')
4、验证同一进程下多线程共享数据
count = 0
def task(x, y, z):
global count
time.sleep(z)
count = y
print(f'{x}开始执行')
print(count)
if __name__ == '__main__':
t = Thread(target=task, args=('线程1', 1, 5))
t2 = Thread(target=task, args=('线程2', 2, 3))
t.start()
t2.start()
print(count)
t.join()
print(count)
t2.join()
print(count)
5、 通过线程互斥锁,实现每次a.txt中的数字减一,防止写乱
def modify(n):
time.sleep(random.randint(1, 3))
with open('mos', 'r', encoding='utf-8') as f:
dic = json.load(f)
print(f'{n}==数字为', dic['count'])
if dic['count'] > 0:
dic['count'] -= 1
with open('mos', 'w',encoding='utf-8') as f:
json.dump(dic, f)
print(f'{n}==减值成功')
else:
print(f'{n}减值失败')
def task(i):
with mutex:
modify(i)
if __name__ == '__main__':
mutex = Lock()
l1 = []
for i in range(10):
t = Thread(target=task, args=(i,))
t.start()
l1.append(t)
for i in l1:
i.join()
6、 利用多进程或多线程自己实现TCP服务端的并发
from multiprocessing import Process
import socket
def task(conn):
while True:
try:
data = conn.recv(1024)
if len(data) == 0: break
print(data)
conn.send(data.upper())
except Exception as e:
print(e)
break
conn.close()
if __name__ == '__main__':
server = socket.socket()
server.bind(('127.0.0.1', 8081))
server.listen(5)
while True:
conn, addr = server.accept()
t=Process(target=task,args=(conn,))
t.start()
import socket
import time
cli=socket.socket()
cli.connect(('127.0.0.1',8081))
while True:
cli.send(b'hello world')
time.sleep(0.1)
data=cli.recv(1024)
print(data)