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线程执行终止

 1 import os
 2 import threading
 3 import time
 4 import logging
 5 import random
 6
 7 def work1():
 8     count=0
 9     while count<=5:
10         threadname= threading.currentThread()
11         wait_time=random.randrange(1,4)
12         print("%s,count =%s wait for =%s s,time %s "%(threadname,count,wait_time,time.ctime()[-13:]))
13         time.sleep(wait_time)
14         count +=1
15
16 def work2():
17     i=0
18     while i<=5:
19         threadname= threading.currentThread()
20         wait_time=random.randrange(1,4)
21         print("%s,i     =%s wait for =%s s,time %s "%(threadname,i,wait_time,time.ctime()[-13:]))
22         time.sleep(wait_time)
23         i +=1
24
25 if __name__ =="__main__":
26     mainthread= threading.currentThread()
27     print ‘%s main thread is waiting for exit‘% mainthread
28     test1=threading.Thread(name=‘work1‘,target=work1)
29     test2=threading.Thread(name=‘work2‘,target=work2)
30     test1.start()
31     test2.start()
32     test1.join()
33     test2.join()
34     print ‘main thread finish‘

  

2个线程设定超时时间work1 5s,work2 4s,9s之后调用线程结束而不等待超时的线程:

 1 import os
 2 import threading
 3 import time
 4 import logging
 5 import random
 6
 7 def work1():
 8     count=0
 9     while count<=5:
10         threadname= threading.currentThread()
11         wait_time=random.randrange(1,4)
12         print("%s,count =%s wait for =%s s,time %s "%(threadname,count,wait_time,time.ctime()[-13:]))
13         time.sleep(wait_time)
14         count +=1
15
16 def work2():
17     i=0
18     while i<=5:
19         threadname= threading.currentThread()
20         wait_time=random.randrange(1,4)
21         print("%s,i     =%s wait for =%s s,time %s "%(threadname,i,wait_time,time.ctime()[-13:]))
22         time.sleep(wait_time)
23         i +=1
24
25 if __name__ =="__main__":
26     mainthread= threading.currentThread()
27     print ‘%s main thread is waiting for exit‘% mainthread
28     test1=threading.Thread(name=‘work1‘,target=work1)
29     test2=threading.Thread(name=‘work2‘,target=work2)
30     test1.start()
31     test2.start()
32     test1.join(4)
33     test2.join(5)
34     print ‘main thread finish

 2.Producer and comsumer

 1 import Queue
 2 import threading
 3 import random
 4
 5 #writelock =threading.Lock()
 6 class Producer(threading.Thread):
 7     def __init__(self,q,con,name):
 8         super(Producer,self).__init__()
 9         self.q = q
10         self.con = con
11         self.name = name
12         print "produce" +self.name+"started"
13     def run(self):
14         while 1:
15             #global writelock
16             self.con.acquire()#acquire the lock
17             if self.q.full():#if queue is full
18                #with writelock:#output info
19                print "queue is full, producer wait"
20                self.con.wait()#wait for resource
21             else:
22                 value = random.ranint(0,10)
23                 #with writelock:
24                 print self.name+"put value"+self.name+":"+str(value)+"into queue"
25             self.q.put((self.name+":"+str(value)))#put to queue
26             self.con.notify()#inform consumer
27         self.con.release()#release the lock
28
29 class Consumer(threading.Thread):
30     def __init__(self,q,con,name):
31         super(Consumer,self).__init__()
32         self.q = q
33         self.con = con
34         self.name = name
35         print "consume" +self.name+"started\n"
36     def run(self):
37         while 1:
38             #global writelock
39             self.con.acquire()
40             if self.q.empty():#if empty
41                 #with writelock:
42                 print "queue is empty,consumer wait"
43                 self.con.wait()#wait the resource ready
44             else:
45                 value = self.q.get()#get one element from queue
46                 #with writelock:
47                 print self.name +"get value"+ value+"from queue"
48                 self.q.notify()#inform producer
49             self.con.release()#release the lock
50
51
52 if __name__ == "__main__":
53     print "start to run\n"
54     q = Queue.Queue(10)
55     con = threading.Condition()
56     p = Producer(q,con,"p1")
57     p.start()
58     p1 = Producer(q,con,"p2")
59     p1.start()
60     c1 = Consumer(q,con,"c1")
61     c1.start()
62
63
64
65
66
67     

3.待续......

时间: 2024-10-11 08:57:34

Python Thread related的相关文章

TLS 与 python thread local

TLS 先说TLS( Thread Local Storage),wiki上是这么解释的: Thread-local storage (TLS) is a computer programming method that uses static or global memory local to a thread. 线程本地存储(TLS)是一种电脑编程技术, 它用静态或者全局的存储器来保存线程本地的变量(意译). 其目的是为了实现变量隔离,即“同一个”全局变量,对于不同的线程,其值可以不同(类似

Python thread start (C source code)

Python源码剖析中针对进程的封装: static PyMethodDef thread_methods[] = { {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread, METH_VARARGS, start_new_doc}, {"start_new", (PyCFunction)thread_PyThread_start_new_thread, METH_VARARGS, st

Python——thread

该模块在Python 3中更名为 _thread. 该模块实现对Python多线程的低层次操作原语,也提供了多线程之间用于同步的锁机制.threading 模块基于本模块提供了更易用的高层次线程API.Windows.Linux.SGI IRIX.Solaris 2.x.和支持 POSIX thread (a.k.a. “pthread”) 的平台都支持该模块,对于不支持 thread 模块的平台,使用 dummy_thread 作为替代. 该模块中定义的常量和函数 exception thre

python thread local的用法

python 中多线程的并发跟其他语言一样,需要考虑多线程并发访问去全局变量所带来的问题,python的local类解决了这个问题,通过它让每个线程内部有一个相对独立的local保存数据,某一个线程修改了数据,不影响其他线程中保存的数据. 1 from threading import Thread 2 import threading 3 import time 4 local_value=threading.local() 5 local_value.x='en' 6 class threa

python thread 多线程

thread 模块在python3中改为_thread,网上的各种帖子都说不建议新手使用thread,好吃不好吃总得尝尝看. 1 import _thread 2 3 def print_num(): 4 for i in range(100): 5 print(i) 6 7 _thread.start_new_thread(print_num,()) 8 _thread.start_new_thread(print_num,()) 9 _thread.start_new_thread(prin

python thread模块 锁 同步锁

Python中的线程是操作系统的原生线程,Python虚拟机使用一个全局解释器锁(Global Interpreter Lock)来互斥线程对Python虚拟机的使用.为了支持多线程机制,一个基本的要求就是需要实现不同线程对共享资源访问的互斥,所以引入了GIL.GIL:在一个线程拥有了解释器的访问权之后,其他的所有线程都必须等待它释放解释器的访问权,即使这些线程的下一条指令并不会互相影响.在调用任何Python C API之前,要先获得GILGIL缺点:多处理器退化为单处理器:优点:避免大量的加

Python Thread

lock 对象: acquire():负责取得一个锁.如果没有线程正持有锁,acquire方法会立刻得到锁.否则,它闲意态等锁被释放. 一旦acquire()返回,调用它的线程就持有锁. release(): 释放锁.如果有其他线程正等待这个锁(通过acquire()),当release()被效用的时候,它们中的一个线程就会 被唤醒 join() Thread setDaemon()

Python thread &amp; process

线程 点击查看 <- 进程 点击查看 <- 线程与进程的区别 线程共享内部空间:进程内存空间独立 同一个进程的线程之间可以直接交流:两个进程之间想通信必须通过一个中间代理 创建新线程很简单,占用资源较少:创建新进程是对父进程的克隆,会占用很多资源 一个线程可以控制和操作同一进程里的其他线程:但是进程只能操作子进程 修改父线程可能会影响到进程下其他线程的行为:但是修改父进程对子进程没有任何影响 线程过多会使 CPU 切换过于频繁,降低运行效率:进程过多会占用大量资源 协程 点击查看 <-

[python]多线程模块thread与threading

Python通过两个标准库(thread, threading)提供了对多线程的支持 thread模块 import time import thread def runner(arg): for i in range(6): print str(i)+':'+arg time.sleep(1) #结束当前线程 thread.exit_thread() #等同于thread.exit() #启动一个线程,第一个参数为函数名, #第二个参数为一个tuple类型,是传给函数的参数 thread.st