Python: 多线程与互斥锁

目录

一、在 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()

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值