开发者

adding a trailing comma to a print command makes threads executions "serialized"

without dumping tones of code here is the symptom

having a threads which all run various methods of the same type of object. within the methods i have a print line which reads:

print self.args, self.foo

everything works just fine.

However, if i turn that line into:

# remain in the same line

print self.args, self.foo,

execution is done in a serialize way and it seems like that print statement blocks other threads from being executed until it finishes.

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 "...thre开发者_如何学Pythonad appendd."


Try flushing stdout after the print

sys.stdout.flush()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜