由于Python 解析器的GIL 问题,多线程的效率并不理想。于是 python 提供了 multiprocessing 模块让你向创建线程一样创建进程,非常方便。但是也有一个问题,那就是如果父进程打开文件,在创建子进程前没有关闭,那么子进程也会占用这个文件,即使在子进程中关闭也无用。
testFile = None
def empty_process(queue, fileno):
if testFile:
testFile.close()
print "run under linux"
else:
print "run under win32"
try:
os.close(fileno)
except:
traceback.print_exc()
queue.put('OK')
def test_process1():
queue = multiprocessing.Queue()
testFile = open('a.txt','a+')
p = Process(target=empty_process, args=(queue, testFile.fileno() ))
p.start()
print queue.get()
try:
testFile.close()
os.unlink('a.txt')
except:
traceback.print_exc()
p.join()
上面这段代码,os.unlink('a.txt') 一定会失败,在子进程中无法关闭testFile。
在网上搜索了好长时间终于找到办法了。
def test_process2():
queue = multiprocessing.Queue()
testFile = open('a.txt','a+')
if sys.platform == "win32":
win32api.SetHandleInformation(
msvcrt.get_osfhandle(testFile.fileno()),
win32con.HANDLE_FLAG_INHERIT,
0)
p = Process(target=empty_process, args=(queue, testFile.fileno() ))
p.start()
print queue.get()
try:
testFile.close()
os.unlink('a.txt')
except:
traceback.print_exc()
p.join()
windows上通过 SetHandleInformation 解决。linux还没有研究过,等下回有空研究研究。