博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 中使用 with 自动获取和释放锁 Lock
阅读量:4228 次
发布时间:2019-05-26

本文共 703 字,大约阅读时间需要 2 分钟。

import threadingimport time num=0  #全局变量多个线程可以读写,传递数据mutex=threading.Lock() #创建一个锁 class Mythread(threading.Thread):    def run(self):        global num        with mutex:   #with Lock的作用相当于自动获取和释放锁(资源)            for i in range(1000000): #锁定期间,其他线程不可以干活                num+=1        print(num) mythread=[]for i  in range(5):    t=Mythread()    t.start()    mythread.append(t)for t in mythread:    t.join()print("game over") '''with mutex:   #with表示自动打开自动释放锁    for i in range(1000000): #锁定期间,其他人不可以干活        num += 1# 上面的和下面的是等价的if mutex.acquire(1):#锁住成功继续干活,没有锁住成功就一直等待,1代表独占    for i in range(1000000): #锁定期间,其他线程不可以干活        num+=1    mutex.release() #释放锁 类似于文件操作的f.close()# 与Python中的with open很像,'''

 

转载地址:http://ydjqi.baihongyu.com/

你可能感兴趣的文章
Uncertainty and Information: Foundations of Generalized Information Theory
查看>>
Professional Web APIs with PHP: eBay, Google, Paypal, Amazon, FedEx plus Web Feeds
查看>>
Cases on Information Technology Planning, Design And Implementation
查看>>
SQL For Dummies
查看>>
Data Structures for Game Programmers
查看>>
Hacking Google Maps and Google Earth
查看>>
Code Design for Dependable Systems: Theory and Practical Applications
查看>>
Elements of Information Theory
查看>>
Mastering Data Warehouse Aggregates: Solutions for Star Schema Performance
查看>>
Digital Multimedia Perception and Design
查看>>
Dreamweaver 8 All-in-One Desk Reference For Dummies
查看>>
JavaScript Design
查看>>
Beginning Mac OS X Tiger Dashboard Widget Development
查看>>
Professional Live Communications Server
查看>>
Microsoft Exchange Server 2003 Advanced Administration
查看>>
Performance Analysis of Communications Networks and Systems
查看>>
SQL Server CE Database Development with the .NET Compact Framework
查看>>
Service Design for Six Sigma: A Roadmap for Excellence
查看>>
Maximum Security (3rd Edition)
查看>>
Discovering Knowledge in Data: An Introduction to Data Mining
查看>>