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的更多相关文章

  1. TLS 与 python thread local

    TLS 先说TLS( Thread Local Storage),wiki上是这么解释的: Thread-local storage (TLS) is a computer programming m ...

  2. python thread的join方法解释

    python的Thread类中提供了join()方法,使得一个线程可以等待另一个线程执行结束后再继续运行.这个方法还可以设定一个timeout参数,避免无休止的等待.因为两个线程顺序完成,看起来象一个 ...

  3. 【Python@Thread】queue模块-生产者消费者问题

    python通过queue模块来提供线程间的通信机制,从而可以让线程分项数据. 个人感觉queue就是管程的概念 一个生产者消费者问题 from random import randint from ...

  4. 【Python@Thread】Semaphore&糖果机

    信号量适用与多线程竞争有限资源的情况. from atexit import register from time import ctime, sleep from threading import ...

  5. 【Python@Thread】锁示例

    当出现竞态条件时候,即在同一个时刻只有一个线程可以进入临界区,需要使用同步. 常见的同步原语有两种:锁/互斥,信号量. 锁是最简单,最低级的机制. 首先看一个不使用锁时候的多线程示例: from at ...

  6. 【Python@Thread】threading模块

    theading模块的Thread类 属性: name 线程名 ident 线程标识符 daemon  布尔值,标示是否为守护线程 方法: __init__(target=None, name=Non ...

  7. 【Python@Thread】thread模块

    一.关于Python多线程 Python解释器中可以同时运行多个线程,但是再任意时刻只能有一个线程在解释器运行. Python虚拟机的访问是由全局解锁器(GIL)控制的,由GIL保证同时只有一个线程的 ...

  8. Python thread local

    由于GIL的原因,笔者在日常开发中几乎没有用到python的多线程.如果需要并发,一般使用多进程,对于IO Bound这种情况,使用协程也是不错的注意.但是在python很多的网络库中,都支持多线程, ...

  9. test for python thread

    #!/usr/bin/python # -*- coding: UTF-8 -*- import thread import time # 为线程定义一个函数 def print_time(threa ...

随机推荐

  1. Codeforces Round B. Buttons

    Manao is trying to open a rather challenging lock. The lock has n buttons on it and to open it, you ...

  2. java.lang.NoClassDefFoundError: javax/el/ELResolver 问题解决

    HTTP Status 500 - java.lang.NoClassDefFoundError: javax/el/ELResolver type Exception report message ...

  3. 不可变字符串NSString

    /*字符串的常用方法*/ //1.通常用来把一些基本数据类型和字符串进行拼接 ; float b = 9527.0; NSString *string = [NSString stringWithFo ...

  4. HTML当中特殊字符的表示

    (回车换行) <br> (空格符)   &(AND符号) & <(左尖括号.小于号) < >(右尖括号.大于号) > °(度) ° •(间隔符) • ...

  5. MySQL每天自动增加分区

    有一个表tb_3a_huandan_detail,每天有300W左右的数据.查询太慢了,网上了解了一下,可以做表分区.由于数据较大,所以决定做定时任务每天执行存过自动进行分区. 1.在进行自动增加分区 ...

  6. C#中(int)、int.Parse()、int.TryParse()和Convert.ToInt32()的区别

    转自:http://www.cnblogs.com/leolis/p/3968943.html 在编程过程中,数据转换是经常要用到的,C#中数据转换的方法很多,拿将目标对象转换为 整型(int)来讲, ...

  7. JAVA中的TreeSet

    TreeSet简介 TreeSet是一个有序的集合,它的作用是提供一个有序的Set集合,它继承于AbstractSet抽象类实现了NavigableSet<E>, Cloneable, j ...

  8. MySQL优化性能my.cnf详解

    提供一个MySQL 5.6版本适合在1GB内存VPS上的my.cnf配置文件(点击这里下载文件): [client] port=3306 socket=/tmp/mysql.sock [mysqld] ...

  9. 树莓派+移动硬盘搭建NAS服务器

    由于树莓派的USB接口不足以给移动硬盘供电,因此需要另外给移动硬盘提供电源. 显示当前已有的存储设备 # fdisk -l Disk /dev/mmcblk0: 7876 MB, 7876902912 ...

  10. Eclipse修改编码格式

    ♣修改工作空间默认编码 ♣修改文件的编码 ♣修改某文件类型的编码 ♣修改JSP文件类型的编码 1.修改工作空间默认编码 window -> preferences ->  General ...