之前用多线程的时候看见了很多文章,比较常用的大概就是join()和setDeamon()了。

先说一下自己对join()的理解吧:

def join(self, timeout=None):
"""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.

When the timeout argument is present and not None, it should be a
floating point number specifying a timeout for the operation in seconds
(or fractions thereof). As join() always returns None, you must call
isAlive() after join() to decide whether a timeout happened -- if the
thread is still alive, the join() call timed out.

When the timeout argument is not present or None, the operation will
block until the thread terminates.

A thread can be join()ed many times.

join() raises a RuntimeError if an attempt is made to join the current
thread as that would cause a deadlock. It is also an error to join() a
thread before it has been started and attempts to do so raises the same
exception.

"""
源码的__doc__其实说的很清楚,join()会阻塞调用该线程的线程,知道该线程结束(This blocks the calling thread
until the thread whose join() method is called terminates)。
注意点:
#coding:utf-8
import threading
import time

def action(arg):
    time.sleep(1)
    print  'sub thread start!the thread name is:%s    ' % threading.currentThread().getName()
    print 'the arg is:%s   ' %arg
    time.sleep(1)

#不正确写法,会导致多线程顺序执行,失去了多线程的意义
for i in xrange(4):
    t =threading.Thread(target=action,args=(i,))
    t.setDaemon(True)
    t.start()
    t.join()

#正确写法
thread_list = []    #线程存放列表
for i in xrange(4):
    t =threading.Thread(target=action,args=(i,))
    t.setDaemon(True)
    thread_list.append(t)

for t in thread_list:
    t.start()

for t in thread_list:
    t.join()


print 'main_thread end!'

下面再说一下setDeamon()吧:

其实主线程并不会结束setDeamon(True)的线程,而是当主线程执行完毕之后不会再去关注setDeamon(True)的线程。

所以setDeamon(True)的线程的结果是我们无法获取到的,类似于爱咋咋地?不管你输出什么,我都不看,主线程跑

完就结束整个python process。

而setDeamon(False)的线程会一直受到主线程的关注,就算主线程跑完了也会等setDeamon(False)的线程跑完然后

再结束整个python process。

所以说,就算setDeamon(True)的线程在主线程之后跑完,但如果在setDeamon(False)的线程之前跑完的话,也是会

输出结果的,而不是被所谓的主线程结束就杀死setDeamon(False)的线程。

附上我的调试代码,

# -*- coding:utf-8 -*-


import threading
import time

stime = time.time()


def action(arg):
    time.sleep(1)
    print ('the arg is:%s,time is %s   ' % (arg, time.time()))


def action1(arg):
    time.sleep(1)
    print ('the arg is:%s,time is %s   ' % (arg, time.time()))


thread_list = []  # 线程存放列表
for i in [777, 888]:
    t = threading.Thread(target=action, args=(i,))
    t.setDaemon(False)
    thread_list.append(t)
for i in range(10):
    t = threading.Thread(target=action1, args=(i,))
    t.setDaemon(True)
    thread_list.append(t)

for t in thread_list:
    t.start()

print('**************')
etime = time.time()
print('time cost is %s' % (etime - stime))

 

 posted on 2018-11-08 17:54  アルタイル  阅读(841)  评论(0编辑  收藏  举报