python多线程上锁

xiaoxiao2021-02-28  72

一般谈到多线程就会涉及到上锁的问题, 为什么要上锁? 是为了线程安全. 比方说我有两个线程, 都要拿到一个唯一的数据(只能被拿一次), 如果不上锁, 那么就很有可能两个线程同时拿, 数据就被拿了两次. 如果我们上锁, 我们就限制了拿的操作在某个时间只能有一个线程做, 如果这个时候其他线程也想做就得等待. 这样就保证了线程安全.

线程不安全的例子:

import threading, time a = 1 def get(): global a if(a): time.sleep(1) print(a) a -= 1 threads = [] for i in range(0, 10): t = threading.Thread(target = get) threads.append(t) for t in threads: t.start() for t in threads: t.join()

本来输出的结果应该只有一个 ’ 1 ’ , 但是实际的输出却有0甚至是负数, 这就是线程不安全造成的, 多个线程同时通过了if判断, 然后输出了异常的值, 所以这个时候我们就需要上锁

import threading, time a = 1 lock = threading.Lock() def get(): global a lock.acquire() if(a): time.sleep(1) print(a) a -= 1 lock.release() threads = [] for i in range(0, 10): t = threading.Thread(target = get) threads.append(t) for t in threads: t.start() for t in threads: t.join()

这样一来结果就对了

转载请注明原文地址: https://www.6miu.com/read-35920.html

最新回复(0)