python线程锁(thread)学习示例
时间:2021-02-09 09:45:23
# encoding: UTF-8
import thread
import time
# 一个用于在线程中执行的函数
def func():
for i in range(5):
print 'func'
time.sleep(1)
# 结束当前线程
# 这个方法与thread.exit_thread()等价
thread.exit() # 当func返回时,线程同样会结束
# 启动一个线程,线程立即开始运行
# 这个方法与thread.start_new_thread()等价
# 第一个参数是方法,第二个参数是方法的参数
thread.start_new(func, ()) # 方法没有参数时需要传入空tuple
# 创建一个锁(LockType,不能直接实例化)
# 这个方法与thread.allocate_lock()等价
lock = thread.allocate()
# 判断锁是锁定状态还是释放状态
print lock.locked()
# 锁通常用于控制对共享资源的访问
count = 0
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
if lock.acquire():
count += 1
# 释放锁
lock.release()
# thread模块提供的线程都将在主线程结束后同时结束
time.sleep(6)
thread 模块提供的其他方法:
thread.interrupt_main(): 在其他线程中终止主线程。
thread.get_ident(): 获得一个代表当前线程的魔法数字,常用于从一个字典中获得线程相关的数据。这个数字本身没有任何含义,并且当线程结束后会被新线程复用。
thread还提供了一个ThreadLocal类用于管理线程相关的数据,名为 thread._local,threading中引用了这个类。
标签:python,thread,线程锁
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
实战手记:让百万级数据瞬间导入SQL Server
2010-06-07 14:13:00
![](https://img.aspxhome.com/file/UploadPic/20106/201067122858333s.jpg)
手机网站开发必修课[2009总结版]
2010-01-05 17:02:00
![](https://img.aspxhome.com/file/UploadPic/20101/11/nj0d3ofg-63s.jpg)
PHPCMS的使用小结
2023-11-20 20:19:47
python 绘制场景热力图的示例
2022-01-22 07:03:21
![](https://img.aspxhome.com/file/2023/0/80560_0s.jpg)
ASP存储过程应用全接触
2007-08-18 14:28:00
python re.match函数的具体使用
2023-07-31 13:16:28
![](https://img.aspxhome.com/file/2023/7/60727_0s.png)
如何将Python编译成C语言
2022-01-02 10:49:31
![](https://img.aspxhome.com/file/2023/4/105414_0s.png)
JavaScript 全半角转换
2010-02-04 17:14:00
python爬虫开发之使用python爬虫库requests,urllib与今日头条搜索功能爬取搜索内容实例
2022-01-05 19:39:44
![](https://img.aspxhome.com/file/2023/8/89358_0s.png)
详解Python中常用的激活函数(Sigmoid、Tanh、ReLU等)
2022-03-25 22:45:51
![](https://img.aspxhome.com/file/2023/5/90445_0s.png)
python-try-except:pass的用法及说明
2022-07-21 13:22:24
分享一个pycharm专业版安装的永久使用方法
2023-04-27 17:26:34
![](https://img.aspxhome.com/file/2023/9/101009_0s.jpg)
python tornado使用流生成图片的例子
2023-08-24 07:07:20
CSS系统默认颜色
2009-01-04 16:53:00
Python实现周期性抓取网页内容的方法
2023-04-12 01:33:36
jupyter notebook 恢复误删单元格或者历史代码的实现
2022-03-03 16:13:45
![](https://img.aspxhome.com/file/2023/2/87562_0s.jpg)
给SQL Server传送数组参数的变通办法
2008-11-25 11:39:00
python虚拟环境迁移方法
2021-09-13 07:52:51
![](https://img.aspxhome.com/file/2023/0/69000_0s.jpg)
模拟兼容性的 addDOMLoadEvent 事件
2009-07-31 12:37:00
php.ini修改php上传文件大小限制的方法详解
2023-09-11 04:03:12