简体   繁体   中英

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.

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

It sounds like the Reader-Writer Problem:

Heard about semaphors or something like that ;)?

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

The most simple way is to use Semaphores. In .net you can use 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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