python 线程安全互斥锁

参考:https://blog.csdn.net/budong282712018/article/details/79968067
参考:https://www.cnblogs.com/holbrook/archive/2012/03/04/2378947.html
发现多个线程开起来以后,代码执行很长时间后会出错。
思考了下肯定不是逻辑上的问题,因为逻辑上的问题第一次就会出错,而不是很多次以后才出错,而且出错的情况也要看概率。

分析:因为没有加Mutex(即下面的代码没有加互斥锁进行隔离),使得同时在thread中同时访问进行修改的时候出错。方法就是用mutex进行隔离,多个thread每次只有一个可以。

mutex.acquire(0)表示如果拿不到就退出(效果就是线程不会排队)
mutex.acquire(1)表示如果拿不到就挂起进行等待(效果就是之后拿到了会继续执行下去)

import threading
import time
from threading import Thread

mutex = threading.Lock()
def hint_display(self,disply_word):
    if mutex.acquire(0):
        self.HintText.setText(disply_word)
        self.HintText.show()
        time.sleep(0.5)
        self.HintText.hide()
        mutex.release()


def check_Hint_Po(self,check_frame):
    for i in range(0,len(self.receive_time)):
        if self.receive_time[i]==check_frame:
            t1=Thread(target=self.hint_display,args=('发球',))
            #t1=Thread(target=self.hint_display('发球'))
            t1.start()

    for i in range(0,len(self.swing_time)):
        if self.swing_time[i]==check_frame:
            t1=Thread(target=self.hint_display,args=('挥拍',))
            t1.start()
    for i in range(0,len(self.score_time)):
        if self.score_time[i]==check_frame:
            t1=Thread(target=self.hint_display,args=('得分',))
            t1.start()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值