How do I avoid race conditions when appending to a file?

佐手、 提交于 2019-12-24 11:53:32

问题


I'm looking at using PipelineDB for analytics. For data warehousing I want to append all new data to a file, and tail -F it into psql like the examples on the website.

I have multiple data sources, so to get deterministic results, I'd like to append them all to the same input file, where they'll stay in the same order.

Is there a simple, idiomatic way of avoiding race conditions? Something like a single-file server I can pipe data to?

Edit:

Actually, a race condition is exactly what I want. But each line must be atomic, so no single line is ever corrupted. Lines may be interleaved, though.


回答1:


You can simulate a mutex by using mkdir which is atomic create-and-check operation (this is ensured at the kernel level):

# locking example -- CORRECT
# Bourne
lockdir=/tmp/myscript.lock
if mkdir "$lockdir"
then    # directory did not exist, but was created successfully
    echo >&2 "successfully acquired lock: $lockdir"
    # continue script
else
    echo >&2 "cannot acquire lock, giving up on $lockdir"
    exit 0
fi

For more information (and other solutions) take a look to the FAQ:

http://mywiki.wooledge.org/BashFAQ/045




回答2:


You could prepend/wrap all your writes with a mutex by using GNU Parallel like this:

sem --id atomicwrite echo hi >> file

So, to test it, run each of these in separate terminals:

for i in {0..999}; do sem --id atomicwrite echo hi >> file ; done


来源:https://stackoverflow.com/questions/32902055/how-do-i-avoid-race-conditions-when-appending-to-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!