关于python:threading:线程退出完成作业之前

threading : A Thread exit before it finishes the job

我试图理解Python线程的"守护进程"标志。我知道

A thread can be flagged as a"daemon thread". The significance of this
flag is that the entire Python program exits when only daemon threads
are left. The initial value is inherited from the creating thread.

但是在我的例子中,python程序在守护进程线程离开之前就退出了,而线程没有完成它的工作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def ThreadDecorator(f):
    def wrap(*args,**kargs):
        t=Thread(target=f,args=args,kwargs=kargs)
        t.daemon=True
        t.start()
return wrap

@ThreadDecorator
def runSomething(*args,**kwargs):
    i = 0
    attente = 0
    fileName=kwargs['file']
    f=open(fileName,'wt')
    while i < 50000:
        f.write(str(i)+"
"
)
        # attente += 0.2
        # attente += random.randint(1, 60) / 100
        # time.sleep(attente)
        i += 1
    f.close()
    return"Finished"

和主程序

1
2
runSomething("5",file='test1.txt')
runSomething("6",file='test2.txt')

第一个线程只写5000个第一个整数,而第二个线程不写任何数字


我觉得主块应该包含一个pool。一旦所有线程都完成,就可以调用pool.close(),以确保所有线程都已完成执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from multiprocessing import Pool
from datetime import datetime

pool = Pool(processes = 2)
num_workers = 2
curr_worker = 1
val = 5
if (curr_worker < num_workers ):
    file_name = 'test'+str(curr_worker)+'.txt'
    pool.apply_async(run_Something,args=(val,file_name,)))
    curr_worker += 1
    val += 1
else:
    pool.close()
    pool.join()
    curr_worker = 1
    val = 5
print ("Workers returned result", datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

启动守护进程线程后,主进程退出。由于守护进程线程在非守护进程主进程终止时停止,我们看到只有test1.txt有5000条记录。

MAIN的任务是启动以下内容,然后退出:

1
2
runSomething("5",file='test1.txt')
runSomething("6",file='test2.txt')