#Lock
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()
#Semaphore信号量
import threading
import time
v = []
lock = threading.BoundedSemaphore(3) #信号量
def func(arg):
lock.acquire()
print(arg)
time.sleep(0.5)
lock.release()
for i in range(10):
t = threading.Thread(target=func,args=(i,))
t.start()
#Condition
import threading
import time
v = []
lock = threading.Condition() #信号量
def func(arg):
print(‘start’)
lock.acquire()
lock.wait_for()
lock.wait()
print(arg)
time.sleep(0.5)
lock.release()
for i in range(10):
t = threading.Thread(target=func,args=(i,))
t.start()
while True:
num = int(input(’>>>’))
lock.acquire()
lock.notify(num)
lock.release()
#Event
import threading
import time
lock = threading.Event()
def func(arg):
print(‘start’)
lock.wait() #加锁
print(arg)
for i in range(10):
t = threading.Thread(target=func,args=(i,))
t.start()
input(’>>>’)
lock.set()#解锁
lock.clear()#再次锁住
import time
import threading
v = threading.local()
def func(arg):
v.phone = arg
time.sleep(2)
print(v.phone,arg)
for i in range(10):
t = threading.Thread(target=func,args=(i,))
t.start()
from concurrent.futures import ThreadPoolExecutor
import time
def task(a1,a2):
time.sleep(1)
print(a1,a2)
#创建了一个线程池(最多5个线程)
pool = ThreadPoolExecutor(5)
for i in range(100):
#去线程池中申请一个线程,让线程执行task函数
pool.submit(task,i,8)
import queue
q = queue.Queue()#线程安全
q.put(1)
q.put(2)
q.put(3)
v1 = q.get()
print(v1)
#生产者消费者模型
import threading
import queue
import time
q = queue.Queue()
def producer(id):
‘’’
生产者
:return:
‘’’
while 1:
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):
‘’’
消费者
:param id:
:return:
‘’’
while 1:
time.sleep(1)
v1=q.get()
print(‘顾客%s生产了一个包子’%id)
for i in range(1,3):
t = threading.Thread(target=consumer,args=(i,))
t.start()