附加到文件时如何避免竞争条件? [英] How do I avoid race conditions when appending to a file?

查看:27
本文介绍了附加到文件时如何避免竞争条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆