import threading
v = []
def func(arg):
v.append(arg) # 线程安全
print(v)
for i in range(10):
t =threading.Thread(target=func,args=(i,))
t.start()
线程安全
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()
# 不加锁: #加锁后
# 2 9 0 0
# 3 9 1 1
# 0 9 2 2
# 1 9 3 3
# 7 9 4 4
# 5 9 5 5
Lock
import threading
import time
v = []
lock = threading.RLock()
def func(arg):
lock.acquire()
lock.acquire()
v.append(arg)
time.sleep(0.01)
m = v[-1]
print(arg,m)
lock.release()
lock.release()
for i in range(10):
t =threading.Thread(target=func,args=(i,))
t.start()
# 结果:
# 0 0
# 1 1
# 2 2
# 3 3
# 4 4
# 5 5
RLock
import time
import threading
lock = threading.BoundedSemaphore(4) #每次允许通过的个数
def func(arg):
lock.acquire() #加锁
print(arg)
time.sleep(2)
lock.release() #解锁
for i in range(10):
t =threading.Thread(target=func,args=(i,))
t.start()
BoundedSemaphore
import time
import threading
lock = threading.Condition()
# ############## 方式一:输入几个取出来几个 ##############
def func(arg):
print('线程进来了')
lock.acquire()
lock.wait() # 加锁
print(arg)
time.sleep(1)
lock.release() #解锁
for i in range(10):
t =threading.Thread(target=func,args=(i,))
t.start()
while True:
inp = int(input('>>>'))
lock.acquire()
lock.notify(inp)
lock.release()
#结果:
# 线程进来了
# ....
# 线程进来了
# >>>3
# >>>0
# 1
# 2
# 2
# >>>3
# 4
# 4
# >>>5
# 8
# 6
# 7
# 3
# >>>9
# ############## 方式二(输入一次放一个)##############
#
def xxxx():
print('来执行函数了')
input(">>>")
# ct = threading.current_thread() # 获取当前线程
# ct.getName()
return True
def func(arg):
print('线程进来了')
lock.wait_for(xxxx)
print(arg)
time.sleep(1)
for i in range(10):
t =threading.Thread(target=func,args=(i,))
t.start()
#结果
# >> > 线程进来了
# 来执行函数了
# >> > 线程进来了
# 来执行函数了
# >> > 1
# 0
# 2
# 1
# 3
# 2
# 6
Condition
import threading
lock = threading.Event()
def func(arg):
print('线程来了')
lock.wait() # 加锁:红灯
print(arg)
for i in range(10):
t =threading.Thread(target=func,args=(i,))
t.start()
input(">>>>")
lock.set() # 绿灯 获取
lock.clear() # 再次变红灯
for i in range(10):
t =threading.Thread(target=func,args=(i,))
t.start()
input(">>>>")
lock.set() #绿灯 获取
Event
import time
import threading
DATA_DICT = {}
def func(arg):
ident = threading.get_ident() #获取线程ID
DATA_DICT[ident] = arg #{1756: 0, 2636: 1, 8892: 2, 8448: 3, 2344: 4, 7196: 5, 8572: 6, 2268: 7, 2480: 8, 7644: 9}
time.sleep(1)
print(DATA_DICT[ident],arg)
for i in range(10):
t =threading.Thread(target=func,args=(i,))
t.start()
import time
import threading
INFO = {}
class Local(object):
def __getattr__(self, item):
ident = threading.get_ident()
return INFO[ident][item]
def __setattr__(self, key, value):
ident = threading.get_ident()
if ident in INFO:
INFO[ident][key] = value
else:
INFO[ident] = {key:value}
obj = Local()
def func(arg):
obj.phone = arg # 调用对象的 __setattr__方法(“phone”,1)
time.sleep(2)
print(obj.phone,arg)
for i in range(10):
t =threading.Thread(target=func,args=(i,))
t.start()
print(INFO)#{7688: {'phone': 0}, 8972: {'phone': 1}, 5280: {'phone': 2}, 4724: {'phone': 3},
# 8384: {'phone': 4}, 8680: {'phone': 5}, 8220: {'phone': 6}, 9032: {'phone': 7}, 4660: {'phone': 8},
# 528: {'phone': 9}}
View Code
from concurrent.futures import ThreadPoolExecutor
import time
def task(a1,a2):
time.sleep(2)
print(a1,a2)
# 创建了一个线程池(最多5个线程)
pool = ThreadPoolExecutor(5)
for i in range(40):
# 去线程池中申请一个线程,让线程执行task函数。
pool.submit(task,i,8)
import time
import threading
def task(arg):
time.sleep(50)
while True:
num = input('>>>')
t = threading.Thread(target=task,args=(num,))
t.start()
线程
import time
from concurrent.futures import ThreadPoolExecutor
def task(arg):
time.sleep(10)
print("========")
pool = ThreadPoolExecutor(3)
while True:
num = input('>>>')
pool.submit(task,num)
线程池
import time
import queue
import threading
q = queue.Queue() # 线程安全
def producer(id):
"""
生产者
:return:
"""
while True:
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):
"""
消费者
:return:
"""
while True:
time.sleep(1)
v1 = q.get()
print('顾客 %s 吃了一个包子' % id)
for i in range(1,3):
t = threading.Thread(target=consumer,args=(i,))
t.start()
View Code