向打印命令添加尾随逗号使线程执行“序列化”

时间:2010-07-01 20:26:29

标签: python multithreading

没有转储代码的色调是症状

拥有一个所有运行相同类型对象的各种方法的线程。 在方法中我有一个打印行:

print self.args, self.foo

一切正常。

但是,如果我将该行转为:

# remain in the same line

print self.args, self.foo,

执行是以序列化方式完成的,看起来print语句阻止其他线程执行直到它完成。

import threading, time

class Graph2(object):
    def __init__(self, instanceName):
        self.instanceName = instanceName

    def __getattr__(self, name):
        def foo():
            for i in xrange(10):
                #### the tricky line #### 
                # print i, self.instanceName
                print i, self.instanceName,
                time.sleep(1)

        return foo


class GraphThread(threading.Thread):
    def __init__(self, graph, method, *args):
        threading.Thread.__init__(self)
        self.g, self.m, self.args = graph, method, args
        self.results = None

    def run(self):
        print 'm=%s, args=%s' % (self.m, self.args)
        self.results = getattr(self.g, self.m)(*self.args)
        print "...done running method %s, with args %s:"%(self.m,self.args)

methods = ["degree","betweenness","closeness","cocitation","shell_index","evcent","eccentricity","constraint"]
threads=[]

# spawn a new thread for every requesting url
for method in methods:
    print "starting thread for method %s..."%method
    t=GraphThread(Graph2(method),method)
    t.start()
    print "..appending thread..."
    threads.append(t)
    print "...thread appendd."

1 个答案:

答案 0 :(得分:1)

请在打印后尝试刷新stdout

sys.stdout.flush()