本文介绍了在并发环境中追加到文件的末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果以下多个(示例)程序同时运行,需要采取哪些步骤来确保始终正确地将完整"行附加到文件末尾.

What steps need to be taken to ensure that "full" lines are always correctly appended to the end of a file if multiple of the following (example) program are running concurrently.

#!/usr/bin/env python
import random
passwd_text=open("passwd.txt","a+")
u=("jsmith:x:1001:1000:Joe Smith,Room 1007,(234)555-8917,(234)555-0077,jsmith@rosettacode.org:/home/jsmith:/bin/sh",
  "jdoe:x:1002:1000:Jane Doe,Room 1004,(234)555-8914,(234)555-0044,jdoe@rosettacode.org:/home/jdoe:/bin/sh",
  "xyz:x:1003:1000:X Yz,Room 1003,(234)555-8913,(234)555-0033,xyz@rosettacode.org:/home/xyz:/bin/sh")
for i in range(random.randint(1,2)):
  print >> passwd_text, random.choice(u)
passwd_text.close()

并且:即使磁盘已满或已设置ulimit -f",能否保证全部或全部"附加(在 linux/unix 上)?

And: Can an "all or nothing" append be guaranteed (on linux/unix) even if the the disk becomes full, or "ulimit -f" has been set?

(注意类似的问题:如何附加到文件?)

推荐答案

我想这个bug"的讨论 在 python 的普通 open 函数中表明你没有得到 POSIX atomic 保证,但是如果你使用的话你会得到

I think the discussion of this "bug" in python's normal open function suggests that you don't get the POSIX atomic guarantee, but you do if you use

with io.open('myfile', 'a') as f:
    f.write('stuff')

http://docs.python.org/2/library/io.html#io.open

如果操作系统正确地实现了它的 write sys 调用...

if the operating system implements its write sys call correctly...

http://bugs.python.org/issue15723

这篇关于在并发环境中追加到文件的末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-20 01:36