目录
一、在 Python 使用多线程
二、互斥锁&防止死锁
一、在 Python 使用多线程
import threading
import time
import random
class MyThread(threading.Thread):
def __init__(self, name, mutex, arg):
threading.Thread.__init__(self, daemon=True)
self.name = name
self.mutex = mutex
self.arg = arg
def log(self, msg):
print("{0} - {1} - {2}".format(self.name, time.time(), msg))
def sleep(self):
time.sleep(random.randint(1, 5))
def run(self):
for i in range(10):
self.log("do something")
self.sleep()
self.mutex.acquire()
self.arg['count'] = self.arg.get('count', 0) + 1
self.mutex.release()
def test_thread():
mutex = threading.Lock()
arg = dict()
arg['count'] = 0
for i in range(10):
t = MyThread(str(i), mutex, arg)
t.start()
while True:
if arg.get('count', 0) >= 10:
break
time.sleep(0.5)
print("end and exit")
if "__main__" == __name__:
test_thread()
二、互斥锁&防止死锁
上述代码中,self.mutex.acquire() 就是在加锁,self.mutex.release() 就是在释放锁。
如果在加锁和释放锁的中间代码中,可能会抛出异常,那么可能导致互斥锁被死锁。此时可以使用下面的代码加以保护:
try:
mutex.acquire()
# some code mybe raise exception
except Exception as e:
print(e)
finally:
mutex.release()
?
|