附加到文件后,如何避免竞争条件? [英] How do I avoid race conditions when appending to a file?
问题描述
我正在考虑使用 PipelineDB 进行分析。对于数据仓库,我想将所有新数据附加到文件中,然后像示例一样,将 tail -F
放入 psql
在网站上。
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?
编辑:
实际上,这是一种竞争条件正是我想要想要的。但是每一行都必须是原子的,因此不会损坏任何一行。但是,行可能是交错的。
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.
推荐答案
您可以使用GNU Parallel像这样用互斥锁来添加/包装所有写操作:
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
这篇关于附加到文件后,如何避免竞争条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!