0
// thread function for readers
void func_readers()
{
    for (int i = 0; i < 1000000; ++i)
    {
        read_lock();
        //do some work;
    }
}

// thread function for writers
void func_writers()
{
    write_lock();
    // do some work;
}

假设有 4 个读取器线程,写入器线程开始工作。它停止了,因为有 4 个阅读线程。当第一个读取线程完成一个迭代时,它会启动另一个,并调用 read_lock()。写入线程仍在等待,因为有 3 个读取线程。由于没有写入线程,因此第一个读取线程开始另一个迭代,依此类推......这是否意味着所有 4 个线程很可能会完成 1000000 次的工作,并且只有在那个写入线程开始工作之后?

4

1 回答 1

0

I believe in this situation, if the reader and writer threads share the same lock, the writer will still have a chance to write something. Think of it as this under the hood:

Let's say reader1 currently has the lock. Reader2, reader3, and reader4 are all on a queue waiting for the lock. It's at this point that writer also puts itself on the queue to wait for the lock. Once reader1 finishes, it releases the lock, and then puts itself back on the queue. However, note that at this point, it's on the queue after the writer.

Once reader2, reader3, and reader4 are popped off the queue and do their work, the writer will have the chance to acquire the lock.

Although this code isn't very efficient (it will basically run serially), it will work. Also, since you're on this topic, you should look into different implementations of reader/writer using multiple locks, counters, etc. :)

于 2017-12-07T05:55:03.340 回答