简体   繁体   English

如何在用C ++写入磁盘的程序中实现并行性?

[英]How can I achieve parallelism in a program that is writing to the disk in C++?

I have a buffer in main memory that contains a couple of files that I want to write in parallel(if possible?) to the disk. 我在主内存中有一个缓冲区,其中包含一些我想并行写入(如果可能的话)到磁盘的文件。 I read and write to different location every time. 我每次都在不同的位置读写。

This is my code: 这是我的代码:

#include <thread>
void t1(){//read from the buffer and writes the 1st file to the disk }
void t2(){//same with the second one }
void t3(){//3rd}
void t4(){//4th}

int main(){
  std::thread thread1(t1);
  std::thread thread2(t2);
  std::thread thread3(t3);
  std::thread thread4(t4);

  t1.join();
  t2.join();
  t3.join();
  t4.join();
}

I know that I can do in parallel the reading of the buffer but the write is the bottleneck. 我知道我可以并行读取缓冲区,但是写入是瓶颈。 Is there I way that I parallelise the write to the disk? 有什么办法可以并行化对磁盘的写入? Is there anything else that I can do to have better performance ? 我还能做些什么来获得更好的性能?

Thanks 谢谢

EDIT: Every thread is writing to a different file. 编辑:每个线程正在写入一个不同的文件。

It very much depends on the data you want to write. 这在很大程度上取决于您要写入的数据。

Writing fixed-sized data you could split it up into four chunks, and each thread seeks to a specific position in the file and write there. 写入固定大小的数据时,您可以将其分为四个块,每个线程都将查找到文件中的特定位置并将其写入。 Note that you need four different file stream objects, one per thread. 请注意,您需要四个不同的文件流对象,每个线程一个。

Writing data without a fixed size, like arbitrary text, is not possible to do in parallel. 没有固定大小的数据写入,例如任意文本,是不可能并行执行的。 You need some kind of synchronization for this so only one thread writes at a time. 为此,您需要某种同步,因此一次只能写入一个线程。

Also, even if the data is a fixed size, it might not be possible to write in parallel, if the data is streaming and can't be split up into chunks. 同样,即使数据是固定大小的,如果数据正在流式传输且无法拆分成块,也可能无法并行写入。


The above is if you want all threads to write to the same file. 以上是如果您希望所有线程都写入同一文件。 If the threads each write to different files then it's no problem. 如果每个线程都写入不同的文件,那就没有问题。 That's no different that multiple processes writing to different files. 多个进程写入不同的文件没有什么不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM