并发和并行
并行是指两个或者多个事件在同一时
刻发生。并行指的是多个cpu
,并发主要针对一个cpu
而已。
并发是指两个或者多个事件在同一时间段
发生。并发的目的是充分利用处理器的每一核
,以达到最高的处理性能。

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| import time from threading import Thread
def sleep_task(sleep_time): print(f"sleep {sleep_time} seconds start!") time.sleep(sleep_time) print(f"sleep {sleep_time} seconds end!")
if __name__ == '__main__': start_time = time.time()
t1 = Thread(target=sleep_task, args=(2,)) t1.setDaemon(True) t1.start()
t2 = Thread(target=sleep_task, args=(3,)) t2.setDaemon(True) t2.start()
end_time = time.time() print("last_time:", end_time-start_time)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class SleepThread(Thread): def __init__(self, sleep_time): self.sleep_time = sleep_time super().__init__()
def run(self): print(f"sleep {self.sleep_time} seconds start") time.sleep(self.sleep_time) print(f"sleep {self.sleep_time} secods end")
if __name__ == '__main__': t1 = SleepThread(2) t2 = SleepThread(3)
t1.start() t2.start()
|
#GIL
什么是GIL
GIL遇到io操作就会释放,切换到线程B、线程C


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| from threading import Thread total = 0
def add(): global total for i in range(1000000): total += 1
def desc(): global total for i in range(1000000): total -= 1
if __name__ == '__main__': add_thread = Thread(target=add) desc_thread = Thread(target=desc)
add_thread.start() desc_thread.start() add_thread.join() desc_thread.join() print(total)
|
线程同步
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
|
from threading import Thread, Lock
total = 0 total_lock = Lock()
# 线程同步:意思也就是我们运行代码的时候不会被中断 # 比如做库存时 就需要加锁,否则时间片
def add(): # 调用acquire就会阻塞住 total_lock.acquire() global total for i in range(1000000): total += 1 # 释放锁 total_lock.release()
def desc(): total_lock.acquire() global total for i in range(1000000): total -= 1 total_lock.release()
if __name__ == '__main__': add_thread = Thread(target=add) desc_thread = Thread(target=desc)
add_thread.start() desc_thread.start()
add_thread.join() desc_thread.join() print(total)
|