简体   繁体   English

正确互斥线程

[英]Correct mutual exclusion of threads

How to organize the synchronization between the threads in the problem below? 在下面的问题中如何组织线程之间的同步?

I have two threads, a writer and a reader. 我有两个主题,一个作家和一个读者。 They both work with the shared resource. 它们都使用共享资源。 When the reader ask for the data chunk, writer starts writing or exit if the transfer is finished. 当读取器要求数据块时,如果传输完成,写入器将开始写入或退出。 Then, when all data chunk is written, the writer waits for the next reader's request. 然后,当所有数据块都写入后,写入器将等待下一个读取器的请求。 The reader waits until the data chunk is ready or until the writer is finished. 读取器等待,直到数据块准备就绪或写入器完成为止。 So, there is the mutual exclusion of both threads. 因此,两个线程相互排斥。

I can't use yield and etc for the task, because the language does not support it. 我不能将yield等用于该任务,因为该语言不支持它。

W     -----         /---------\
R----/     \--------           --------

It sounds like the Reader-Writer Problem: 听起来像读写器问题:

Heard about semaphors or something like that ;)? 听说过信号灯或类似的东西;)?

http://en.wikipedia.org/wiki/Readers-writers_problem http://en.wikipedia.org/wiki/Readers-writers_problem

The most simple way is to use Semaphores. 最简单的方法是使用信号量。 In .net you can use locking . 在.net中,可以使用locking

A semaphore is the "classical" way to lock data. 信号量是锁定数据的“经典”方式。

Depending on your specific requirements, you might actually have better lock with one of the "thread safe collections" (System.Collections.Concurrent) provided in newer versions of .Net: 根据您的特定要求,实际上,您可以使用.Net较新版本中提供的“线程安全集合”(System.Collections.Concurrent)之一更好地锁定:

If not all of your threads are updating data, you can also achieve performance gains with reader/writer locks (vs. "simple locking"): 如果不是所有线程都在更新数据,则还可以通过读取器/写入器锁定(相对于“简单锁定”)来提高性能:

'Hope that helps 希望有帮助

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

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