python 线程之_thread

_thread module:

基本用法:

 def child(tid):
print("hello from child",tid)
_thread.start_new_thread(child,(1,)

1 使用_thread.start_new_thread() 方法来开始一个新的线程。这个调用接收一个函数对象(或其他可调用对象)和一个参数元组。这非常类似与python的function(*args)调用语法

类似的也可以接受一个关键字参数字典。

2 从操作的角度来说_thread.start_new_thread()的调用本身返回一个没有用的值。在函数调用结束后退住,如果在函数的调用过程中发生了异常会打印堆栈跟踪记录其他部分继续运     行。

3. 使用_thread启动线程的其他方法:

 import _thread

 def action(i):
print(i ** 32) class Power:
def __init__(self,i):
self.i = i
def action(self):
print(self.i ** 32) _thread.start_new_thread(action,(2,)) _thread.start_new_thread(lambda:action(2), ()) obj = Power()
_thread.start_new_thread(obj.action,())

运行多个线程及同步访问共享对象:

在多个线程运行的过程中,如果涉及到一个线程访问修改了一个全局作用域变量,那么这个改变对于此进程中的其他线程是可见的。

好处:使程序的线程间传递信息很简单,所谓的自带任务间通信机制。

坏处:需要注意数个线程同时改变全局对象和名称。如果有两个线程一起改变某个共享的对象,那么可能丢失一个或者共享对象的状态被损坏。

使用锁的概念可以确保在任何一个时间点只有一个线程持有锁。如果在持有期间其他线程请求获得锁,那么这个请求会被一直阻塞,直到释放此锁。

1. 使用_thread.allocate_lock创建一个锁对象可又多个线程轮流获取和释放

 import _thread
import time def counter(threadid, count):
for i in range(count):
time.sleep(1)
mutex.acquire()
print('thread id [{0}] => {1}'.format(threadid, i))
mutex.release()
for i in range(5):
_thread.start_new_thread(counter, (i, 5)) mutex = _thread.allocate_lock() time.sleep(7)
print('main process exit')

2. 在上面的代码中,主线程为了等待所有的子线程完成后在退出使用time.sleep(7)这样的方式,可以使用等待线程退出的其他方式来更灵活的等待。

1. 针对每一个线程创建相应的锁对象,形成锁列表,在线程函数运行之后,获取这个锁对象,在主线程对这个列表进行循环判断。如果所有的锁都是获取状态那么主线程可以退出,反之需要等待所有线程完成之后退出。

 import _thread
import time count = 5
mutex = _thread.allocate_lock()
exitmutexs = [_thread.allocate_lock() for i in range(count)] def child(threadid,count):
for i in range(count):
time.sleep(1)
mutex.acquire()
print('[{0}] => {1}'.format(threadid, i))
mutex.release()
exitmutexs[threadid].acquire() for i in range(count):
_thread.start_new_thread(child, (i, 5)) for m in exitmutexs:
while not m.locked(): pass print('main thread exiting')

2. 上面的代码有点大财效用,通过检查锁的locked方法来查看状态。但是主线程仅仅关注所有的锁被获取,其实可以简单使用包含列表而非锁的方式来达到相同的效果

 import _thread
import time threadNum = 5
mutex = _thread.allocate_lock()
#使用bool的标识列表来判断
exitmutexex = [False] * threadNum def counter(threadid, count):
for i in range(count):
time.sleep(1)
mutex.acquire()
print('[{0}] => {1}'.format(threadid, i))
mutex.release()
exitmutexex[threadid] = True #向主线程发出信号 for i in range(threadNum):
_thread.start_new_thread(counter, (i, 5)) while False in exitmutexex:pass #判断所有线程是否完成
print('main process existing')

3. 在上面的两个脚本存在的问题,I 主线程在繁忙等待中切换,这样在紧凑的程序可能导致显著的性能下降。这个可以使用time.sleep()替换pass

II 使用with语句可以获取锁然后在执行完成之后自动释放锁。

 import _thread
import time threadNum = 5
mutex = _thread.allocate_lock()
exitmutexes = [_thread.allocate_lock() for i in range(5)] def counter(threadid, count):
for i in range(count):
time.sleep(1)
with mutex:
print('[{0}] => {1}'.format(threadid, i))
exitmutexes[threadid].acquire() for i in range(threadNum):
_thread.start_new_thread(counter,(i, 5)) while not all(m.locked() for m in exitmutexes): time.sleep(0.25)
print('main process existing')

python 线程之_thread的更多相关文章

  1. python 线程之 threading(四)

    python 线程之 threading(三) http://www.cnblogs.com/someoneHan/p/6213100.html中对Event做了简单的介绍. 但是如果线程打算一遍一遍 ...

  2. python 线程之 threading(三)

    python 线程之 threading(一)http://www.cnblogs.com/someoneHan/p/6204640.html python 线程之 threading(二)http: ...

  3. python 线程之 threading(一)

    threading:基于对象和类的较高层面上的接口,threading模块在内部使用_thread模块来实现线程的对象以及常用的同步化工具的功能. 使用定制类的方式继承 threading.Threa ...

  4. python 线程之threading(五)

    在学习了Event和Condition两个线程同步工具之后还有一个我认为比较鸡肋的工具 semaphores 1. 使用semaphores的使用效果和Condition的notify方法的效果基本相 ...

  5. python 线程之 threading(二)

    在http://www.cnblogs.com/someoneHan/p/6204640.html 线程一中对threading线程的开启调用做了简单的介绍 1 在线程开始之后,线程开始独立的运行直到 ...

  6. python线程之condition

    cond = threading.Condition() # 类似lock.acquire() cond.acquire() # 类似lock.release() cond.release() # 等 ...

  7. python 多线程编程之_thread模块

    参考书籍:python核心编程 _thread模块除了可以派生线程外,还提供了基本的同步数据结构,又称为锁对象(lock object,也叫原语锁.简单锁.互斥锁.互斥和二进制信号量). 下面是常用的 ...

  8. iOS多线程之8.NSOPeration的其他用法

      本文主要对NSOPeration的一些重点属性和方法做出介绍,以便大家可以更好的使用NSOPeration. 1.添加依赖 - (void)addDependency:(NSOperation * ...

  9. Java多线程之ConcurrentSkipListMap深入分析(转)

    Java多线程之ConcurrentSkipListMap深入分析   一.前言 concurrentHashMap与ConcurrentSkipListMap性能测试 在4线程1.6万数据的条件下, ...

随机推荐

  1. DB2用一张表更新其他表的数据

    表结构: CREATE TABLE ATEST  (ID    INTEGER,   NAME  VARCHAR(256),   CODE  INTEGER,   NAME2 VARCHAR(256) ...

  2. C# 操作IIS方法集合

    如果在win8,win7情况下报错:未知错误(0x80005000) 见http://blog.csdn.net/ts1030746080/article/details/8741399 using ...

  3. SQL Server 子查询

    这些主要是老师上课讲的一些知识点,自己做了一些整理放在这里~~~ 子查询可以是标量的.多值的或是表值的. 在期待单个值的地方可以使用标量子查询.例如,以下查询返回具有最大员工编号的员工信息: SELE ...

  4. poj 3735 Training little cats 矩阵快速幂+稀疏矩阵乘法优化

    题目链接 题意:有n个猫,开始的时候每个猫都没有坚果,进行k次操作,g x表示给第x个猫一个坚果,e x表示第x个猫吃掉所有坚果,s x y表示第x个猫和第y个猫交换所有坚果,将k次操作重复进行m轮, ...

  5. CodeSign error: code signing is required for product type Application in SDK iOS

    在真机测试的时候往往会突然出现这样一个错误,code signing is required for product type 'Application' in SDK 'iOS 7.0'  ,就是说 ...

  6. 闭包(block)

    block主要解决反向传值和传值问题 1.block申明的公式       返回值类型 (^名字)(参数列表); 2.block实现的公式       名字= ^(参数列表){}; 3.局部变量   ...

  7. self dismissModalViewControllerAnimated:YES 无效(dismissviewcontrolleranimated无效)

    作为一个viewController(VC),想要消失的时候可以从parent VC里面调用dismissModalViewControllerAnimated来消去改VC,也可以在该VC里面手动调用 ...

  8. 数据存储--sqlite总结

    SQLite SQLite(轻量级的数据库,关系型数据库) 辅助工具:Navicat Premium 等 原理:ios针对存储问题封装了sqlite数据库(c语言数据库). 1 app获取沙盒地址命名 ...

  9. Java Eclipse进行断点调试

    如何调试Java程序? 大家最开始学习Java,都会觉得IDE调试好高端有木有,其实很简单了. 下文会尽量简单直观的教会你在Eclipse中调试,其他的IDE调试步骤也是类似的. 1.在你觉得有错的地 ...

  10. Linux常用命令学习1---(安装、文件系统、目录操作命令cd ls mv cp rm mkdir、链接命令ln……)

    1.理解Linux的文件系统:分区和挂载点    挂载点和路径名无关 /根目录下的/boot完全可以时独立于 /的独立的挂载点,只要你设置就可以    linux安装时候,必须要有这两个分区 / 和 ...