线程同步,谁能给我算法?
我的任务是用C编写一个加密程序。
有一个源文件和一个目标文件。我的程序 需要从源文件中读取内容,对其进行加密并 将加密内容写入目标文件。
我的程序中有7个线程。
三个线程一行一行读取源文件并放入文件内容 进入共享缓冲区 1,线程从共享缓冲区 1 读取内容,对其进行加密 并放入共享缓冲区2,另外三个线程读取加密内容 从共享缓冲区 2 并将其写入目标文件。
我的想法是创建两个 mutices 以确保只有一个线程可以读取 源文件或同时写入目标文件。我的问题是如何控制多个线程对共享缓冲区 1、共享缓冲区 2 的访问。我知道它像生产者/消费者问题一样退出,但更复杂。有人可以给我建议吗?提前致谢。
My task is to write a encrypted program in C.
There is a source file and a target file.My program
need read content from source file, encrypt them and
write encrypted content to target file.
There are 7 threads in my program.
Three threads read the source file one line by one line and put contents of file
into a shared buffer 1, a thread reads contents from shared buffer 1, encrypts it
and puts into a shared buffer 2, and another three threads read encrypted content
from shared buffer 2 and write it into target file.
My thinking is to create two mutices to ensure that there is just one thread can read from
source file or write to target file at same time. My problem is how can I control access by multiple threads to a shared buffer 1, shared buffer 2. I know it is quit like a Producer/consumer problem but more complex. Anyone can give me advice? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在boost示例中,您有一个关于互斥锁、共享内存和多线程通信的非常好的示例,此处。
此示例使用共享内存来存储来自一个线程的消息,而另一个线程读取这些消息,从而阻止共享内存进行并发访问。您可以申请您的主题。
You have a very good example about mutex, shared memory and multi-threading communications in boost examples, here.
This example use a shared memory for storing messages from one tread and another one read them, blocking the shared memory for concurrent access. You can apply for your threads.