線程鎖
---1---線程鎖:當有一個數據有多個線程都可以對其進行修改的時候,任何一個線程改變它都會對其他線程造成影響,
如果我們某一個線程在使用完之前,其他線程不能對其修改,就需要對這個線程增加一個線程鎖
代碼實現
count = 0
def get_money(money):
global count
count += money
count += money
count -= money
lock = threading.Lock()
def lock_thread(money):
# acquire 捕獲
#加鎖
lock.acquire()
time.sleep(random.randint(1,3))
print('當前線程爲',threading.current_thread().name)
get_money(money)
time.sleep(random.randint(1,3))
print('當前線程爲', threading.current_thread().name)
#解鎖
lock.release()
#創建線程 的參數爲一個 元組類型
# 主線程 開闢一個分線程
thread1 = threading.Thread(target=lock_thread,name='thread1',args=(1000,))
thread2 = threading.Thread(target=lock_thread,name='thread2',args=(2000,))
thread1.start()
thread2.start()
print('hello world')
# join注重的整體,線程1沒有執行完,線程2不能執行
# lock注重的是局部 某一個變量沒有用完 其他線程不能使用
thread1.join()
thread2.join()
執行結果:
---2---線程隊列
代碼實現:
import queue
#創建一個線程隊列
# 隊列:FIFO first in first out 先進先出
q = queue.Queue()
for i in range(5):
# 將內容放置到線程隊列中
q.put(i)
while not q.empty():
print(q.get())
print('------------------------------------------')
#LIFO last in first out 後進先出
p = queue.LifoQueue()
for i in range(5):
p.put(i)
while not p.empty():
print(p.get())
執行結果: