Python线程,奇怪的结果

时间:2014-04-01 14:29:35

标签: multithreading python-2.7

我正在测试python线程的工作原理,我期待这些进程能够启动并完成,但它并不是我得到的。这是一个简单的脚本:

import threading
import time
import random


def loop_fn():
    for i in range(1, 5):
        n = random.randint(1,5)
        print "process", i," started "
        time.sleep(n)
        print "process", i," finished"

threading.Thread(target=loop_fn).start()
print "end"

结果显示离线,多次运行后 (Windows环境):

<1st program run>
%run threading1.py
end
process 1  started 

<2nd program run>
%run threading1.py
process 1  finished
process 2  started 
process 2  finished
process 3  started 
processend 1  started 

<3rd program run>
%run threading1.py
process 3  finished
process 4  started 
process 4  finished
endprocess 1  started 

任何提示?

1 个答案:

答案 0 :(得分:1)

如果您希望进程1到5并行运行,则需要为每个进程创建一个线程,而不是为所有五个进程创建一个线程。如果您希望线程在程序终止之前完成执行,那么主线程应该join每个工作线程。

import threading
import time
import random

def loop_fn(i):
    n = random.randint(1,5)
    print "process", i," started "
    time.sleep(n)
    print "process", i," finished"

threads = []
for i in range(1, 5):
    t = threading.Thread(target=loop_fn, args=(i,))
    t.start()
    threads.append(t)

for t in threads:
    t.join()
print "end"

结果:

process 1  started process
 2  started process
 3process  4 started
 started
processprocess  32   finished finished

processprocess 1   finished4
 finished
end

如果您想要更好的输出,可以选择使用Lock进行打印。这将阻止一个线程开始打印,而另一个线程已完成打印。

import threading
import time
import random

print_lock = threading.Lock()
def atomic_print(msg):
    print_lock.acquire()
    print msg
    print_lock.release()


def loop_fn(i):
    n = random.randint(1,5)
    atomic_print("process {} started ".format(i))
    time.sleep(n)
    atomic_print("process {} finished".format(i))

threads = []
for i in range(1,5):
    t = threading.Thread(target=loop_fn, args=(i,))
    t.start()
    threads.append(t)

for t in threads:
    t.join()
print "end"

结果:

process 1 started
process 2 started
process 3 started
process 4 started
process 1 finished
process 2 finished
process 4 finished
process 3 finished
end