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()
阅读全文
0 0
- python使用互斥锁同步线程
- python多线程编程: 使用互斥锁同步线程
- python多线程编程: 使用互斥锁同步线程
- python多线程编程: 使用互斥锁同步线程
- python多线程编程: 使用互斥锁同步线程
- python多线程编程: 使用互斥锁同步线程
- Python线程同步--互斥锁
- python多线程编程(3): 使用互斥锁同步线程
- python多线程编程(3): 使用互斥锁同步线程
- python多线程编程(3): 使用互斥锁同步线程
- python多线程编程(3): 使用互斥锁同步线程
- python多线程编程(3): 使用互斥锁同步线程
- Python使用条件变量保持线程同步
- Python多线程使用及线程同步
- Python 线程同步
- Python 线程同步队列
- python线程同步方法
- python线程同步
- java-14-String类
- Vue.js解析(十一)【说说element组件库broadcast与dispatch】
- Linux中软连接和硬链接
- 4-2 电子时钟中的运算符重载
- 集合相等问题
- python使用互斥锁同步线程
- 1.2 换行输出
- 2017.11.16
- 笔记:elasticsearch在项目中的使用需求
- 浅谈堆和栈的区别
- xgboost 解释
- Oracle 服务器 客户端 US7ASCII、 UTF8字符编码问题
- 小明的存钱计划
- FPGA 查找表和寄存器等详解