python使用互斥锁同步线程

来源:互联网 发布:windows 打开dos 编辑:程序博客网 时间:2024/06/05 04:18
#!/usr/bin/env pythonimport threadingimport timeclass MyThread(threading.Thread):        def run(self):                global num                time.sleep(1)                num=num+1                msg=self.name+'set num to'+str(num)                print msgnum=0def test():        for i in range(5):                t=MyThread()                t.start()if __name__=='__main__':        test()~

线程同步能够保证多个线程安全访问竞争资源,最简单的同步机制是引入互斥锁。互斥锁为资源引入一个状态:锁定/非锁定。某个线程要更改共享数据时,先将其锁定,此时资源的状态为“锁定”,其他线程不能更改;直到该线程释放资源,将资源的状态变成“非锁定”,其他的线程才能再次锁定该资源。互斥锁保证了每次只有一个线程进行写入操作,从而保证了多线程情况下数据的正确性。

#创建锁
mutex = threading.Lock()
#锁定
mutex.acquire([timeout])
#释放
mutex.release()

#!/usr/bin/env pythonimport threadingimport timeclass MyThread(threading.Thread):        def run(self):                global num                time.sleep(1)                if mutex.acquire(1):                        num=num+1                        msg=self.name+'set num to'+str(num)                        print msg                        mutex.release()num=0mutex=threading.Lock()def test():        for i in range(5):                t=MyThread()                t.start()if __name__=='__main__':        test()


原创粉丝点击