Python Thread related

1.Thread.join([timeout])
Wait until the thread terminates. This blocks the calling thread until the thread whose join() method is called terminates – either normally or through an unhandled exception – or until the optional timeout occurs.
等待进程结束。也就是说,其屏蔽调用线程,直到此线程方法终止(要么正常执行完毕,或者未处理的异常,或者时间超时)
下面通过例子来说明:
没有设定timeout情况,Main 线程启动,work1 和work2 线程执行,完毕退出,Main线程执行终止
import os
import threading
import time
import logging
import random def work1():
count=0
while count<=5:
threadname= threading.currentThread()
wait_time=random.randrange(1,4)
print("%s,count =%s wait for =%s s,time %s "%(threadname,count,wait_time,time.ctime()[-13:]))
time.sleep(wait_time)
count +=1 def work2():
i=0
while i<=5:
threadname= threading.currentThread()
wait_time=random.randrange(1,4)
print("%s,i =%s wait for =%s s,time %s "%(threadname,i,wait_time,time.ctime()[-13:]))
time.sleep(wait_time)
i +=1 if __name__ =="__main__":
mainthread= threading.currentThread()
print '%s main thread is waiting for exit'% mainthread
test1=threading.Thread(name='work1',target=work1)
test2=threading.Thread(name='work2',target=work2)
test1.start()
test2.start()
test1.join()
test2.join()
print 'main thread finish'

2个线程设定超时时间work1 5s,work2 4s,9s之后调用线程结束而不等待超时的线程:
import os
import threading
import time
import logging
import random def work1():
count=0
while count<=5:
threadname= threading.currentThread()
wait_time=random.randrange(1,4)
print("%s,count =%s wait for =%s s,time %s "%(threadname,count,wait_time,time.ctime()[-13:]))
time.sleep(wait_time)
count +=1 def work2():
i=0
while i<=5:
threadname= threading.currentThread()
wait_time=random.randrange(1,4)
print("%s,i =%s wait for =%s s,time %s "%(threadname,i,wait_time,time.ctime()[-13:]))
time.sleep(wait_time)
i +=1 if __name__ =="__main__":
mainthread= threading.currentThread()
print '%s main thread is waiting for exit'% mainthread
test1=threading.Thread(name='work1',target=work1)
test2=threading.Thread(name='work2',target=work2)
test1.start()
test2.start()
test1.join(4)
test2.join(5)
print 'main thread finish
2.Producer and comsumer
import Queue
import threading
import random #writelock =threading.Lock()
class Producer(threading.Thread):
def __init__(self,q,con,name):
super(Producer,self).__init__()
self.q = q
self.con = con
self.name = name
print "produce" +self.name+"started"
def run(self):
while 1:
#global writelock
self.con.acquire()#acquire the lock
if self.q.full():#if queue is full
#with writelock:#output info
print "queue is full, producer wait"
self.con.wait()#wait for resource
else:
value = random.ranint(0,10)
#with writelock:
print self.name+"put value"+self.name+":"+str(value)+"into queue"
self.q.put((self.name+":"+str(value)))#put to queue
self.con.notify()#inform consumer
self.con.release()#release the lock class Consumer(threading.Thread):
def __init__(self,q,con,name):
super(Consumer,self).__init__()
self.q = q
self.con = con
self.name = name
print "consume" +self.name+"started\n"
def run(self):
while 1:
#global writelock
self.con.acquire()
if self.q.empty():#if empty
#with writelock:
print "queue is empty,consumer wait"
self.con.wait()#wait the resource ready
else:
value = self.q.get()#get one element from queue
#with writelock:
print self.name +"get value"+ value+"from queue"
self.q.notify()#inform producer
self.con.release()#release the lock if __name__ == "__main__":
print "start to run\n"
q = Queue.Queue(10)
con = threading.Condition()
p = Producer(q,con,"p1")
p.start()
p1 = Producer(q,con,"p2")
p1.start()
c1 = Consumer(q,con,"c1")
c1.start()
3.Queue
programming python 4th 205页
Queue 提供标准的队列数据结构,实现python对象的先进先出,其可包含基本类型(string,list,dictionary......),类实例,任何可调用函数或绑定的方法等。但是Queue不像正常的list,因为其自动被线程获取和释放锁操作。
#coding:utf-8"
import logging,threading,time
import Queue def fibo_task(cond):
with cond:
while shared_queue.empty():
logger.info("[%s]- waiting for element in queue......" % threading.current_thread().name)
cond.wait()
else:
value =shared_queue.get()
a,b=0,1
for item in range(value):
a,b=b,a+b
fibo_dict[value] = a
shared_queue.task_done()
time.sleep(2)
logger.debug("[%s] fibo of key[%d] with result[%d]" % (threading.current_thread().name,value,fibo_dict[value])) def queue_task(cond):
logging.debug('starting list data to queue......')
with cond:
for data in impit_list:
shared_queue.put(data)
#[shared_queue.put(data) for data in impit_list]
cond.notifyAll() if __name__ == "__main__":
logger =logging.getLogger()
logger.setLevel(logging.DEBUG)
formatter =logging.Formatter('%(asctime)s =%(message)s') ch=logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(formatter)
logger.addHandler(ch)
fibo_dict={}
shared_queue =Queue.Queue()
impit_list =[3,10,5,7]
queue_cond=threading.Condition()
print "main thread starting......"
threads =[threading.Thread(target=fibo_task,args=(queue_cond,)) for i in range(4)]
#for thread in threads:
#thread.setDaemon(True)
#print 'daemon is %d' % thread.isDaemon() [thread.start() for thread in threads] prod = threading.Thread(name='queue_task_thread',target=queue_task,args=(queue_cond,))
prod.setDaemon(True)
prod.start() [thread.join() for thread in threads]
print "main thread done"
Python Thread related的更多相关文章
- TLS 与 python thread local
TLS 先说TLS( Thread Local Storage),wiki上是这么解释的: Thread-local storage (TLS) is a computer programming m ...
- python thread的join方法解释
python的Thread类中提供了join()方法,使得一个线程可以等待另一个线程执行结束后再继续运行.这个方法还可以设定一个timeout参数,避免无休止的等待.因为两个线程顺序完成,看起来象一个 ...
- 【Python@Thread】queue模块-生产者消费者问题
python通过queue模块来提供线程间的通信机制,从而可以让线程分项数据. 个人感觉queue就是管程的概念 一个生产者消费者问题 from random import randint from ...
- 【Python@Thread】Semaphore&糖果机
信号量适用与多线程竞争有限资源的情况. from atexit import register from time import ctime, sleep from threading import ...
- 【Python@Thread】锁示例
当出现竞态条件时候,即在同一个时刻只有一个线程可以进入临界区,需要使用同步. 常见的同步原语有两种:锁/互斥,信号量. 锁是最简单,最低级的机制. 首先看一个不使用锁时候的多线程示例: from at ...
- 【Python@Thread】threading模块
theading模块的Thread类 属性: name 线程名 ident 线程标识符 daemon 布尔值,标示是否为守护线程 方法: __init__(target=None, name=Non ...
- 【Python@Thread】thread模块
一.关于Python多线程 Python解释器中可以同时运行多个线程,但是再任意时刻只能有一个线程在解释器运行. Python虚拟机的访问是由全局解锁器(GIL)控制的,由GIL保证同时只有一个线程的 ...
- Python thread local
由于GIL的原因,笔者在日常开发中几乎没有用到python的多线程.如果需要并发,一般使用多进程,对于IO Bound这种情况,使用协程也是不错的注意.但是在python很多的网络库中,都支持多线程, ...
- test for python thread
#!/usr/bin/python # -*- coding: UTF-8 -*- import thread import time # 为线程定义一个函数 def print_time(threa ...
随机推荐
- package.json 字段全解析
Name 必须字段. 小提示: 不要在name中包含js, node字样: 这个名字最终会是URL的一部分,命令行的参数,目录名,所以不能以点号或下划线开头: 这个名字可能在require()方法中被 ...
- grunt 一个目录下所有的js文件压缩 配置收藏
module.exports = function(grunt){ // 项目配置 grunt.initConfig({ pkg: grunt.file.readJSON('package.json' ...
- java单例模式的几种写法比较
概念: Java中单例模式是一种常见的设计模式,单例模式的写法有好几种,这里主要介绍三种:懒汉式单例.饿汉式单例.登记式单例. 单例模式有以下特点: 1.单例类只能有一个实例. 2.单例类必须自己创建 ...
- [转]as3中的SharedObject的保存路径
SharedObject的保存路径 Windows XP 网络访问: C:\Documents and Settings\[你的用户名]\Application Data\Macromedia\Fla ...
- [IOS]译Size Classes with Xcode 6: One Storyboard for all Sizes
Size Classes with Xcode 6: One Storyboard for all Sizes 为所有的尺寸准备一个Storyboard 我最喜欢的Xcode6的特性是新的size c ...
- 动态设置AndroidManifest.xml文件中的meta-data
当debug和release版本使用不同的值时,使用Gradle设置相应的值. Android主配置文件 <meta-data android:name="com.amap.api.v ...
- union的限制, 临时表大小的优化
- Struts2 OGNL 字符串自定义转化对象细节
要使用Struts2的自定义对象转化,需要几个要点: 1.要有继承DefaultTypeConverter的实现类,要重写convertValue,并且参数value转化而来的String是Strin ...
- Vmware安装Centos NAT方式设置静态IP
[Vmware中在搭建集群环境等,DHCP自动获取IP方式不方便,为了固定IP减少频繁更改配置信息,建议使用静态IP来配置,网络连接主要有三种方式 1.nat 2.桥接,3主机模式 ,在这里主要介NA ...
- iOS版本更新的App提交审核发布流程
http://www.2cto.com/kf/201502/378698.html 版本更新的App和新App的发布提交流程略有不同,新的App需要在开发者账号里准备发布证书,添加App的id,关联描 ...