import threading
import time
ticket=20
#创建一把锁,线程锁。
lock= threading.Lock()
def sell_tocket():
global ticket
while True:
lock.acquire()#加锁
if ticket>0:
time.sleep(1)
ticket -=1
lock.release()#解锁
print('{}卖出一张票,还剩{}张'.format(threading.current_thread().name,ticket))
else:
lock.release()
print('票卖完了')
break
t1=threading.Thread(target=sell_tocket,name='线程1')#target参数是一个函数,不加括号,加了之后就变成了函数执行了
t2=threading.Thread(target=sell_tocket,name='线程2')
t1.start()
t2.start()
线程间的通信
import threading
import time
import queue
def produce():
for i in range(10):
time.sleep(1)
print('{}生产---面包{}'.format(threading.current_thread().name,i))
q.put('{}{}'.format(threading.current_thread().name,i))
def costomer():
for i in range(10):
time.sleep(0.3)
#q.get()是一个阻塞方法
print('{}买到----面包{}'.format(threading.current_thread().name,q.get()))
# 创建一个队列对象
q = queue.Queue()
#生产线
pa = threading.Thread(target=produce,name='pa')
#消费线
ca = threading.Thread(target= costomer,name='ca')
pa.start()
ca.start()
多进程
import multiprocessing,time
def dance(n):
for i in range(n):
time.sleep(0.5)
print('正在跳舞')
def sing(m):
for i in range(m):
time.sleep(1)
print('正在唱歌')
if __name__=='__main__':
#创建俩个进程
#tagrget 用来表示执行的任务
#args 用来传参,类型是一个元组
p1 = multiprocessing.Process(target=dance,args=(10,))
p2 = multiprocessing.Process(target=sing, args=(10,))
p1.start()
p2.start()
进程间的通信
import os
import multiprocessing
import time
def produce(x):
for i in range(10):
time.sleep(0.5)
print('生产++++{}{}'.format(os.getpid(),i))
x.put('pid{}{}'.format(os.getpid(),i))
def consume(x):
for i in range(10):
time.sleep(0.5)
print('消费-----{}'.format(x.get()))
if __name__=='__main__':
#进程的队列对象是这样写的。需要传参
q=multiprocessing.Queue()
p1=multiprocessing.Process(target=produce,args=(q,))
p1.start()
c1=multiprocessing.Process(target=consume,args=(q,))
c1.start()