首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > perl python >

python threading t.join () 方法解决思路

2012-03-25 
python threading t.join () 方法学习python线程部分发现t1.join()这个方法,书上讲 t.join(timeout)等待

python threading t.join () 方法
学习python线程部分发现t1.join()这个方法,书上讲 "t.join(timeout)等待直到线程终止或者出现超时为止,timeout为浮点数,线程......."

按照书上的理解t1.join()应该是等待线程的结束,而从我的试验结果来看似乎t1.join()在等待线程结束后直接令整个进程都终止了。




附上代码:

  1 from threading import Thread  
  2 import time
  3 
  4 def test1 ( times, sec, yy ):
  5 print str(times) + ' ' + str(sec) + ' ' + yy
  6 for i in range ( times ):
  7 print '%d111111111111111' % i
  8 time.sleep (1)
  9 
 10 def test2 ( times ):
 11 print times
 12 for i in range ( times ):
 13 print '%d22222222222222222222222222' % i
 14 time.sleep ( 1)
 15 
 16 
 17 t1 = Thread ( target = test1, name = 'teTTTTTTTTTTTTTTTTTTTTTst1', args = (20,30), kwargs = {'yy':'345'} )
 18 t2 = Thread ( target = test2, name = 'teRRRRRRRRRRRRRRRRRRRRRst2', args = (5,) )
 19 
 20 t1.daemon = True
 21 t2.daemon = True
 22 
 23 t1.start ()
 24 #t1.join ( 4.0 )
 25 
 26 print t1.name
 27 t2.start ()
 28 t2.join ( ) <<<<<<<<<<<<<<<<<<<<在这里等待t2线程结束
 29 
 30 print t2.name
   
运行结果:


20 30 345teTTTTTTTTTTTTTTTTTTTTTst1

5
022222222222222222222222222
0111111111111111
122222222222222222222222222
 1111111111111111
222222222222222222222222222
 2111111111111111
3111111111111111
 322222222222222222222222222
4111111111111111
 422222222222222222222222222
teRRRRRRRRRRRRRRRRRRRRRst25111111111111111
   

结果是t2运行结束后t1也不能执行......困惑中,求解.....

[解决办法]
主线程A启动了子线程B,调用b.setDaemaon(True),则主线程结束时,会把子线程B也杀死,与C/C++中得默认效果是一样的。 
daemon 
A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when no alive non-daemon threads are left.

热点排行