使用linux上的多线程将数据写入单个文件 [英] Writing the data into single file using multi threading on linux

查看:610
本文介绍了使用linux上的多线程将数据写入单个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个创建多个线程的示例,所有线程都将数据写入单个文件。它应该在继续循环中。如果文件大小为1 KB,则停止程序。



我尝试过:



我尝试创建多个线程,但我无法在所有线程的单个文件中写入数据。

I am looking for an example which creates multiple threads and all threads are writing the data into single file. It should be in continues loop. If file size are 1 KB then stop the program.

What I have tried:

I have tried creating multiple threads but I am not able to write data in a single file from all threads.

推荐答案

在我看来,拥有所有线程写入同一文件的线程不必要地复杂化。我会创建一个1KB缓冲区和一个自定义例程,使用互斥锁或临界区将数据写入其中以控制访问。您的线程可以写入缓冲区,直到其完整,此时线程终止。当发生这种情况时,主线程可以发出信号,然后它可以将数据写入文件并终止进程。这对我来说似乎很简单,只要你知道如何管理线程。
In my opinion, having all the threads write to the same file is unnecessarily complicated. I would make a 1KB buffer and a custom routine to write your data into it with a mutex or critical section to control access. Your threads can write into the buffer until its full at which time the threads terminate. The primary thread could be signaled when that happens and it could then write the data to the file and terminate the process. This seems pretty simple to me as long as you know how to manage threads.


你需要有一个额外的线程。

* Writer,它将数据写入文件。

*你需要有队列,工作线程会将数据推入队列

*两个队列都必须是线程安全的。

*每个工作线程都会生成自己的数据并推送到队列。

* Writer线程将从队列中弹出数据并写入文件。
You need to have One extra threads.
* Writer, that writes data into file.
* You need to have Queue, Worker thread will push data into queue
* Both Queue will have to be thread safe.
* Each worker thread will generate it's own data and push to a queue.
* Writer thread will pop data from Queue and write into files.


这篇关于使用linux上的多线程将数据写入单个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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