2012-02-18 72 views
2

我写了这个小测试类,基于a Python issue - closed/fixed,它似乎在Python 2.7.1在Fedora 15subprocess.Popen不是线程安全的?

from subprocess import Popen, PIPE 
from threading import Thread 

OUTPUT = "asl;dkfhqwiouethnjzxvnhsldfhuyasdhofuiweqamchuisemfawepfhuaipwemhfuaehfclkuehnflw ehfcoiuwehfiuwmhefuiwehfoiuhSfcl hfulh fuiqhuif huiwafh uiahf iUH fhh flkJH fl HASLFuhSAIULFhSUA HFulSAHfOI SUFChiuwqhncriouweycriuowanbyoUIWCryu iWyruawyrouiWYRcoiu YCRoiuNr uyr oUIAWryocIUWRNyc owuroiuNr cuWyrnawueitcnoy U IuiR yiuowaYnorc oWIUAr coiury iuoAW rnuoi asdfsdfd\n" 


class X(Thread): 
    def __init__(self): 
     Thread.__init__(self) 

    def run(self): 
     print("Running") 
     for i in xrange(10): 
      s = Popen(
       "cat /tmp/junk", 
       shell=True, 
       stdout=PIPE, 
       universal_newlines=True 
      ) 
      output = s.communicate()[0] 
      if not output == OUTPUT: 
       print("Error: %r" % output) 


XThreads = set([]) 

for i in xrange(1000): 
    XThreads.add(X()) 

for x in XThreads: 
    x.start() 

发生只需创建一个文件,在这种情况下的/ tmp /垃圾,有OUTPUT的内容,减去最后一个换行符。

运行这个,你会期望看到每一行“运行”。但是,有时会显示“正在运行”或“正在运行\ n \ n正在运行”。

(删除了对实际问题的引用,因为这是一个假症状,这要感谢@ phihag的回答)。

的实际问题:https://stackoverflow.com/questions/9338409/python-subprocess-popen-corrupts-binary-streams

回答

2

你看到的行为无关,与子;我可以重现它:

import threading 
def run(): print("Running") 
for x in [threading.Thread(target=run) for i in range(1000)]: 
    x.start() 

这是因为Python's print is not thread-safe。为了避免打印出的文字和换行之间的竞争条件,直接写入到标准输出,就像这样:

import threading,sys 
def run(): sys.stdout.write("Running\n") 
for x in [threading.Thread(target=run) for i in range(1000)]: 
    x.start() 

这是假设的基本write调用到stdout是线程安全的。 That depends on the platform

+0

谢谢,我想我已经找到了我的问题,但需要上传多个文件以提供一个工作示例 - 不确定如何在此处执行此操作...您能帮忙吗? – CrackerJack9 2012-02-18 03:35:03

+0

更有趣的是,真正的问题 - http://stackoverflow.com/questions/9338409/python-subprocess-popen-corrupts-binary-streams – CrackerJack9 2012-02-18 04:18:08

+0

@ CrackerJack9通过一些修改,你应该能够连接任何多文件Python编入一个。如果这是不可能的(或者程序非常长),请将文件上传到[gist](https://gist.github.com/)或[pastebin](http://pastebin.com) – phihag 2012-02-18 09:50:35