例子:
from multiprocessing.dummy import Pool as ThreadPool
def testfunc(string):
print string
def main():
strings = ['one', 'two', 'three', ...]
pool = ThreadPool(10)
results = pool.map(testfunc, strings)
pool.close()
pool.join()
if __name__ == '__main__':
main()
这不会给我们一个清晰的结果,一行一个结果:
one
two
three
但是 mesh,有随机的换行符,比如
one
two
three
four
five
...
为什么会这样?我可以在每次函数调用时使用一个换行符输出我的数据吗?
附言有时我什至没有换行符甚至空格! 附言在windows下工作
最佳答案
print
是一个非原子操作,因此一个打印可以在中间被不同进程中的另一个打印打断。您可以通过在其周围放置一个 Lock
来防止两个进程同时调用 print
。
from multiprocessing.dummy import Pool as ThreadPool
from multiprocessing import Lock
print_lock = Lock()
def testfunc(string):
print_lock.acquire()
print string
print_lock.release()
def main():
strings = ['one', 'two', 'three', 'four', 'five']
pool = ThreadPool(10)
results = pool.map(testfunc, strings)
pool.close()
pool.join()
if __name__ == '__main__':
main()
关于python - 为什么在使用 python 多处理池时会看到额外的换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26143095/