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 ...
随机推荐
- [机器学习] 虚拟机VMware中使用Ubuntu的联网问题
在VMware中安装Ubuntu要解决两个问题: 1.VMware Tools安装使用 2.Ubuntu联网的虚拟机设置 1.VMware Tools安装 它的作用就是使用户可以从物理主机直接往虚拟机 ...
- MSSQL 死锁查询
SELECT SYS.DM_EXEC_REQUESTS.SESSION_ID,TEXT AS '执行SQL',CLIENT_NET_ADDRESS AS '请求IP',SYS.DM_EXEC_CONN ...
- 判断.NET4.0是否安装
Clinet 和 Full存在一个都说明安装了Framework "SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Client"&qu ...
- CI,从数据库读取数据
1.准备数据库,(用户,密码,数据库服务的地址) 2.CI链接数据库,配置database.php(配置文件) //application/config/database.php 3.准备 ...
- 再谈java两种变量(基本类型和引用类型)(综合各路大神)
基本类型: 基本类型自然不用说了,它的值就是一个数字,一个字符或一个布尔值. int a: a=250: //声明变量a的同时,系统给a分配了数据空间. 引用类型: 是一个对象类型,值是什么呢? ...
- 简单实用JSTL标签库
1. JSTL标签库是一个什么东东? 简单来说,有了它你就可以在类似HTML的JSP页面里面运用一些高级语法,实现迭代.条件判断.XML文档操作.国际化标签.SQL标签. 2. 如何使用 ? 参考网址 ...
- server与Portal联合,portal许可过期无法登录。
server与Portal联合,portal许可过期无法登录,怎样解除联合. 解决方案由峥姐友情提供~~ (1)删除有两种方式(①/②选其一即可): ①类似 链接ttps://sunl.esrichi ...
- 函数式中的 currying
currying 是函数式语言中经常遇到的一个概念,翻译成 柯里化,不是库里化. currying 指的是将接收多个参数的函数变换成接收一个单一参数,并且返回接收余下的参数而且返回结果的新函数的技术. ...
- python中matplotlib画折线图实例(坐标轴数字、字符串混搭及标题中文显示)
最近在用python中的matplotlib画折线图,遇到了坐标轴 "数字+刻度" 混合显示.标题中文显示.批量处理等诸多问题.通过学习解决了,来记录下.如有错误或不足之处,望请指 ...
- C# 日期格式转【转】
使用:DateTime.ToString的方法(String, IFormatProvider)转换格式 using System; using System.Globalization; Strin ...