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. java实现a+b的多重输入

    import java.util.Scanner; public class hello { public static void main(String[] args) { Scanner cin ...

  2. an excellent capability of C# language and compiler

    Sometimes you want to write code that works for different primitive types, and as C# doesn't support ...

  3. CentOS6.7安装RabbitMQ3.6.5

    1.安装所有依赖包yum install -y gcc ncurses ncurses-base ncurses-devel ncurses-libs ncurses-static ncurses-t ...

  4. 二十四点算法 java实现

    问题: 给出四个数,不可以重复使用,可以用+ - * /和括号,怎么得出24? 代码: //return -1 表示当前方法不行 private int workByStep(int op,int n ...

  5. NOIP2015D1

    好像来的有点晚,但我的确现在刚做这套题 T1神奇的幻方 题目描述 幻方是一种很神奇的N*N矩阵:它由数字1,2,3,……,N*N构成,且每行.每列及两条对角线上的数字之和都相同. 当N为奇数时,我们可 ...

  6. uva10986 堆优化单源最短路径(pas)

    var n,m,s,t,v,i,a,b,c:longint;//这道题的代码不是这个,在下面 first,tr,p,q:..]of longint; next,eb,ew:..]of longint; ...

  7. JS正则表达式将url转成json格式

    var url = location.search.substr(1); param = {}; console.log(url); url.replace(/([^?&]+)=([^?&am ...

  8. 利用jquery发送form表单

    $("#rap_save_draft").click(function(){ rap_start_editor.sync();//同步KindEditor的内容 // 取得要提交的 ...

  9. java面向对象_抽象类和接口

    一.抽象类 1.抽象方法:由abstract修饰.只有定义没有方法体.用一个分号结尾. 2.抽象类: 1)包含抽象方法的类必须是抽象类 2)由abstract修饰 3)不能被实例化 4)抽象类如果不被 ...

  10. JS动态引入js,CSS——动态创建script/link/style标签

    一.动态创建link方式 我们可以使用link的方式.如下代码所示. 二.动态创建style方式 但是,这样的话,需要加载整个css文件,但是那样有可能浪费一个http请求并占用一个服务器请求数,并等 ...