python多线程
python多线程
python多线程简介
python多线程时间并非是并行得,而是并发的,是多线程交替执行达到得并发效果
单线程实现食堂打饭操作
需求: 一个人打四份饭耗时
import time
"""
io密集型
"""
foods = 0
import threading
def get_food():
"""
食堂大妈打饭
"""
global foods
time.sleep(1)
foods += 1
print("大妈打了一份饭")
def take_food(name="1"):
"""
学生去打饭
"""
while foods < 4 :
time.sleep(1)
get_food()
time.sleep(1)
print(name + "打饭完成")
t1 = time.time()
take_food()
t2 = time.time()
print("一个人打完4份饭的时间==", t2-t1)
输出结果:
大妈打了一份饭
1打饭完成
大妈打了一份饭
1打饭完成
大妈打了一份饭
1打饭完成
大妈打了一份饭
1打饭完成
一个人打完4份饭的时间== 12.092403650283813
多线程实现食堂打饭
import time
"""
io密集型
"""
import threading
foods = 0
lock = threading.Lock()
def get_food():
"""
食堂大妈打饭
"""
global foods
time.sleep(1)
foods += 1
print("大妈打了一份饭")
def take_food(name="1"):
"""
学生去打饭
"""
global foods, lock
lock.acquire()
time.sleep(1)
get_food()
time.sleep(1)
print(name + "打饭完成")
print("foods值为", foods)
lock.release()
# 多线程
t1 = time.time()
for i in range(3):
th = threading.Thread(target=take_food, args=(str(i),))
th.start()
t2 = time.time()
print("3个人打完4份饭的时间==", t2 - t1)
输出结果:
3个人打完4份饭的时间== 0.0010788440704345703
大妈打了一份饭
0打饭完成
foods值为 1
大妈打了一份饭
1打饭完成
foods值为 2
大妈打了一份饭
2打饭完成
foods值为 3
多线程实现取钱
-
未加锁
import threading
import timebanlence = 800 def with_draw(money,name): global banlence if money <= banlence: banlence -= money print(name + "取钱成功") print("可用余额:", banlence) else: print(name + "取钱失败") th1 = threading.Thread(target=with_draw, args=(500, "张三")) th2 = threading.Thread(target=with_draw, args=(500, "李四")) th1.start() th2.start() """ 输出结果: 张三取钱成功 可用余额: -200 李四取钱失败 """
-
加锁
# 多线程去取钱时数据不安全,需要加锁banlence = 800 lock = threading.Lock() def with_draw(money, name): global banlence, lock # 加锁 lock.acquire() if money <= banlence: time.sleep(0.1) banlence = banlence - money print(name + "取钱成功") print(threading.current_thread().name) print("可用余额:", banlence) else: print(name + "取钱失败") # 释放安全锁. 线程2要使用这个方法时需要等线程1使用完 lock.release() th1 = threading.Thread(target=with_draw, args=(500, "张三")) th2 = threading.Thread(target=with_draw, args=(500, "李四")) th1.start() th2.start() """ 张三取钱成功 Thread-1 可用余额: 300 李四取钱失败 """