c ++多进程写入同一个文件 - 进程间互斥?(c++ multiple processes writing to the same file - Interprocess mutex?)

我的问题是:从多个进程写入文件的最佳方式(或至少是一种有效的方法)是什么?

注意:我正在使用c ++ 11,我希望这可以在任何平台上运行(即纯c ++代码)。

我已经做了一些研究,下面是我所得出的结论:

  1. 在我的进程中,我有多个线程。 这很容易在每个进程中使用互斥来处理对文件的访问。
  2. 一个c ++ / c ++ 11互斥体或条件变量不能用于序列化进程之间。
  3. 我需要某种外部信号量/锁定文件来充当“互斥体”......但我不确定如何去做这件事。

我看到应用程序在使用时会使用诸如创建“.lock”文件之类的东西。 但是对于多次快速访问,似乎这可能不起作用(即,在一个进程已经决定文件不存在之后,另一个进程可以创建它,然后第一个进程也会尝试创建它),因为测试和创建文件的操作是不是原子的。

注意:每个进程一次总是写一整行。 我曾认为这可能足以使操作成为“原子”(因为整行将在下一行之前被缓冲),但似乎并非如此(除非我的代码错误),因为我(很少)得到一条损坏的线。 这里是我如何写一个代码片段(如果它是相关的):

// in c'tor
m_osFile.open("test.txt", std::fstream::out | std::fstream::app)

// in write func (std::string data)
osFile << data<< std::endl;

这肯定是一个常见问题,但我还没有找到一个可行的解决方案。 任何代码片段都会受到欢迎。


My question is this: what is the best way (or at least an effective way) to write to a file from multiple processes?

Note: I am using c++11 and I want this to run on any platform (i.e. pure c++ code only).

I have done some research and here is what I have concluded:

  1. In my processes I have multiple threads. This is easily handled within each process using a mutex to serialise access to the file.
  2. A c++/c++11 mutex or conditional variable cannot be used to serialise between processes.
  3. I need some sort of external semaphore / lock file to act as a "mutex"... but I am not sure how to go about doing this.

I have seen applications use things like creating a ".lock" file when in use. But for multiple rapid access it seems like this may not work (i.e. after one process has decided the file does not exist another could create it and then the first process will also try to create it) because the operation to test and create the file is not atomic.

Note: Each process always writes one entire line at a time. I had thought that this might be enough to make the operation "atomic" (in that a whole line would get buffered before the next one), but this does not appear to be the case (unless I have my code wrong) since I (rarely) get a mangled line. Here is a code snippet of how I am doing a write (in case it is relevant):

// in c'tor
m_osFile.open("test.txt", std::fstream::out | std::fstream::app)

// in write func (std::string data)
osFile << data<< std::endl;

This must be a common-ish issue, but I have not yet found a workable solution to it. Any code snippets would be welcome.


原文:https://stackoverflow.com/questions/49381583
2022-09-23 17:09

满意答案

你可以像下面的代码那样做。 需要进行一些调整以获得您想要的确切结果(如图像),但我相信它会让您顺利进行。

我为'进步'栏添加了一些jQuery。 通过使用data-progress (使用百分比!!!),您可以定义进度的程度。

作为替代方案,您可以将data-progress="90%"更改为style="width: 90%" ,这使其成为100%HTML / CSS。

$(function() {
	$('.progress>div').each(function() {
  	$(this).css('width', $(this).data('progress') );
  });
});
* {
  box-sizing: border-box;
}
body {
  background: white;
}
.project {
  width: 400px;
  margin-bottom: 1em;
}
  .project > div {
    display: inline-block;
    margin: 0 -5px 0 0;
    vertical-align: middle;
  }
.task {
  width: 2em;
  height: 2em;
  border: .4em solid #E4E4E7;
  background: #E4E4E7;
  border-radius: 100%;
}
.progress {
  width: calc( 50% - 3em);
  height: .6em;
  padding: .2em 0;
  background: #E4E4E7;
  position: relative;
}
  .progress>div {
    height: .2em;
    left: -.4em;
    right: -.4em;
    position: absolute;
  }
.pending { background: #F8AC59; }
.running { background: #1C84C6; }
.passed { background: #1AB394; }
.failed { background: #ED5565; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="project">
  <div class="task pending"></div>
  <div class="progress"><div> </div> </div>
  <div class="task"></div>
  <div class="progress"><div> </div></div>
  <div class="task"></div>
</div>

<div class="project">
  <div class="task running"></div>
  <div class="progress"><div class="running" data-progress="90%"> </div> </div>
  <div class="task"></div>
  <div class="progress"><div> </div></div>
  <div class="task"></div>
</div>

<div class="project">
  <div class="task passed"></div>
  <div class="progress"><div class="passed"> </div> </div>
  <div class="task passed"></div>
  <div class="progress"><div class="passed"> </div></div>
  <div class="task passed"></div>
</div>

<div class="project">
  <div class="task failed"></div>
  <div class="progress"><div> </div> </div>
  <div class="task"></div>
  <div class="progress"><div> </div></div>
  <div class="task"></div>
</div>

<div class="project">
  <div class="task passed"></div>
  <div class="progress"><div class="passed"> </div> </div>
  <div class="task passed"></div>
  <div class="progress"><div class="passed"> </div></div>
  <div class="task passed"></div>
</div>

<div class="project">
  <div class="task failed"></div>
  <div class="progress"><div class="failed"> </div> </div>
  <div class="task failed"></div>
  <div class="progress"><div> </div></div>
  <div class="task"></div>
</div>


You could do it like the following code. It will need some tweaking to get the exact result you want (like images), but I believe it will get you on your way.

I've added a little bit of jQuery for 'progress' bars. By using the data-progress (use percentage!!!) you can define how far the progress is.

As an alternative to the you could change the data-progress="90%" to style="width: 90%" which makes it 100% HTML/CSS.

$(function() {
	$('.progress>div').each(function() {
  	$(this).css('width', $(this).data('progress') );
  });
});
* {
  box-sizing: border-box;
}
body {
  background: white;
}
.project {
  width: 400px;
  margin-bottom: 1em;
}
  .project > div {
    display: inline-block;
    margin: 0 -5px 0 0;
    vertical-align: middle;
  }
.task {
  width: 2em;
  height: 2em;
  border: .4em solid #E4E4E7;
  background: #E4E4E7;
  border-radius: 100%;
}
.progress {
  width: calc( 50% - 3em);
  height: .6em;
  padding: .2em 0;
  background: #E4E4E7;
  position: relative;
}
  .progress>div {
    height: .2em;
    left: -.4em;
    right: -.4em;
    position: absolute;
  }
.pending { background: #F8AC59; }
.running { background: #1C84C6; }
.passed { background: #1AB394; }
.failed { background: #ED5565; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="project">
  <div class="task pending"></div>
  <div class="progress"><div> </div> </div>
  <div class="task"></div>
  <div class="progress"><div> </div></div>
  <div class="task"></div>
</div>

<div class="project">
  <div class="task running"></div>
  <div class="progress"><div class="running" data-progress="90%"> </div> </div>
  <div class="task"></div>
  <div class="progress"><div> </div></div>
  <div class="task"></div>
</div>

<div class="project">
  <div class="task passed"></div>
  <div class="progress"><div class="passed"> </div> </div>
  <div class="task passed"></div>
  <div class="progress"><div class="passed"> </div></div>
  <div class="task passed"></div>
</div>

<div class="project">
  <div class="task failed"></div>
  <div class="progress"><div> </div> </div>
  <div class="task"></div>
  <div class="progress"><div> </div></div>
  <div class="task"></div>
</div>

<div class="project">
  <div class="task passed"></div>
  <div class="progress"><div class="passed"> </div> </div>
  <div class="task passed"></div>
  <div class="progress"><div class="passed"> </div></div>
  <div class="task passed"></div>
</div>

<div class="project">
  <div class="task failed"></div>
  <div class="progress"><div class="failed"> </div> </div>
  <div class="task failed"></div>
  <div class="progress"><div> </div></div>
  <div class="task"></div>
</div>

相关问答

更多

HTML5 / CSS3无类框架(HTML5/CSS3 classless framework)

这听起来像你想要的不是一个CSS框架,而只是一个简单的自定义样式表。 不要阻止你寻找已经存在的东西,但你最好自己写。 也许从许多现有的reset.css 。 没有能力通过类名钩住(或离开)的默认样式不是很灵活。 你真的不应该避免上课,你应该利用他们。 没有框架会知道你的HTML元素在哪里和如何嵌套,或者它们根据标签名称应该是什么样子,这就是我们通常使用类的原因之一。 如果您密切关注新的HTML5元素的语义,您会发现该header并不总是意味着“带有徽标的页面顶部”, footer不仅仅是整个页面底...

如何关注HTML5和CSS3中的最新更新[关闭](How to follow the latest updates in HTML5 and CSS3 [closed])

我远离w3schools - 他们不隶属于W3C。 有关详细信息,请访问http://w3fools.com/ 。 一些更好,更可靠的资源是: http://dev.opera.com/articles/view/1-introduction-to-the-web-standards-cur/#toc (面向初学者 - 请参阅HTML5部分) & https://developer.mozilla.org/en-US/docs/HTML/HTML5 (中级更多) I'd stay away fro...

HTML5 / CSS3布局显示任务运行状态[关闭](HTML5/CSS3 layout to show tasks running status [closed])

你可以像下面的代码那样做。 需要进行一些调整以获得您想要的确切结果(如图像),但我相信它会让您顺利进行。 我为'进步'栏添加了一些jQuery。 通过使用data-progress (使用百分比!!!),您可以定义进度的程度。 作为替代方案,您可以将data-progress="90%"更改为style="width: 90%" ,这使其成为100%HTML / CSS。 $(function() { $('.progress>div').each(function() { $(thi...

我如何知道何时使用CSS,ID或HTML5来使用CSS在HTML中进行布局?(How do I know when to use a Class, an ID or HTML5 to make layouts in HTML using CSS? [closed])

把它想象成一所学校 多个学生的课程(多个元素) 单个学生的ID (单个元素) Think of it as a school class for multiple students (multiple elements) id for a single student (single element)

HTML5,CSS3参考[关闭](HTML5, CSS3 reference [closed])

获得基础知识的一个良好开端是阅读Mark Pilgrim的Dive Into HTML5 。 您甚至可以在购买之前尝试,因为它是免费的。 另一个建议是Pro HTML 5编程:用于更丰富的Internet应用程序开发的强大API (非免费)。 对于最全面的阅读,我推荐HTML5规范 ,其中包含所有细节。 Head First HTML5 Programming是迄今为止我见过的新手前端开发人员最好的书。 这是学习HTML5的最佳书籍列表: HTML5:启动并运行 首先是HTML5编程 适用于Mas...

布局网站IE8和下层看起来错了CSS3 [关闭](Layout website IE8 and lower looks wrong CSS3 [closed])

是的,这可能是预期的行为(取决于你正在做的事情),对于IE8来说是完全正常的。 在IE8中,很多HTML5标记/元素都不会被浏览器理解,并且它不知道它是否应该在线显示或作为块显示,并且您需要提供HTML5垫片来处理这些内容。 IE8中支持的CSS选择器规则也很少,在Selectivizr中可以找到如何获得支持的列表。 当然,您需要像JQuery这样的东西来提供支持 还有一些:伪属性不受支持,你需要编写JavaScript来模拟它们并添加适当的样式规则。 IE9以下的IE无法呈现HTML5 / CS...

Android HTML5游戏[关闭](Android HTML5 Games [closed])

您尝试在WebView加载/播放的游戏不是纯HTML5应用程序,而是简单的JavaScript游戏。 要在您自己的WebView ,您需要为此WebView激活JavaScript : WebView myWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); 在我的测试用例中...

HTML5和CSS3在元素焦点上显示表单提示(HTML5 and CSS3 show form hints on element focus)

那么,既然你提到了CSS3,这里有一些CSS3淡入淡出的解决方案。 HTML <label for="username">Username</label> <input type="text" id="username" name="username"> <div class="msg">You need a username that is more than 5 letters long</div> CSS .msg { color:#999; opacity:0; display:in...

HTML5 + CSS3 VS标准HTML 4 [关闭](HTML5 + CSS3 VS Standard HTML 4 [closed])

简而言之: 优点: 支持互动媒体 改进了语义 更直观的开发 缺点: 仅在现代浏览器上支持 首先,要记住语言本身不被认为是完成的关键。 因此,HTML5是早期版本的延续,被认为是对语言的改进。 正如您在问题中提到的那样,HTML5的主要缺点是它仅受现代浏览器的支持(请参阅http://html5test.com/ )。 因此,如果您的目标受众无法访问现代浏览器,HTML5肯定会处于劣势。 这也是使用CSS3的主要缺点。 优势肯定超过利弊。 这是一个很好的资源,概述了使用HTML5的许多差异和优势 -...

如何检查符合html5 / css3的网页[关闭](how to check for html5/css3 compliant web pages [closed])

你总是希望在这里进行测试。 但您也可以定期运行它们。 http://validator.w3.org/ You always want to run tests on here towards the end. But you can also run them periodically. http://validator.w3.org/

相关文章

更多

Java 流(Stream)、文件(File)和IO

Java 流(Stream)、文件(File)和IO Java.io包几乎包含了所有操作输入、输 ...

My W3C Custom Mapping File

[hdhw] HotKey=W Tip=Train Dragonha|cffffcc00w|r ...

C程序访问Hadoop

现在计划做通过C访问Hadoop,选择了LibHDFS,打算用Eclipse(V3.7.2) CDT和 ...

《虚拟机系统与进程的通用平台》(Virtual Machines: Versatile Platforms for Systems and Processes)扫描版[PDF]

中文名: 虚拟机系统与进程的通用平台 原名: Virtual Machines: Versati ...

shell 脚本执行,出现错误bad interpreter: No such file or directory

出现bad interpreter:No such file or directory的原因 是文件格 ...

《C/C++图像处理编程》扫描版[PDF]

中文名: C/C++图像处理编程 作者: 陆宗骐 图书分类: 网络 资源格式: PD ...

Android 微信的回调跨进程间的调用 (分享)

微信平台开放后倒是挺火的,许多第三方应用都想试下,毕竟可以利用微信建立起来的关系链来拓展自己的应用还是 ...

C++ Hadoop实战备忘

前言:Hadoop用于解决大数据处理问题。看到这么火,咱也来凑把热闹,瞧瞧到底是什么神奇的技术。 实战 ...

Python内建函数(C)

callable(object) 说明:检查对象object是否可调用。如果返回True,ob ...

java server怎样和c++ client实现SSL通信??

java keytool生成的证书是CRT等格式的,这种格式是2进制编码的,而C++用的证书格式是pe ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本