User:Cljbx/Readers–writers problem

计算机科学中读者 - 编写者问题是一种在并发常见的一种计算问题的例子。 问题至少有三种变体,计算机在处理多个线程同时尝试访问同一共享资源的情况。 有些线程可能会读取资源而有些线程可能会写入资源,该问题的限制条件是当一个进程对共享资源进行读取或写入时,另一个进程无法写入它。 (它可以被两个或更多的读者进程在同一时间访问,但只能被唯一的写者进程访问, 读写器锁是一种解决一个或多个读者 - 写者问题的数据结构

基本的读者-作家问题由库尔图瓦 et al.[1][2]第一次形式化并解决的。

例如:假设在一个班级只有一个布告板,只有一个人可以进行编写,与此同时,许多读者可以稍后阅读布告板。

假设我们有一个受以上基本制约的共享内存区。 可以通过互斥锁保证没有两个线程可以在同一时间访问词数据。 然而,这种解决方案是低效的,因为当读者 R1 加锁,然后另一个读者 R2 请求访问。 R2 将进行等待,无法在 R1 完成之前开始自己的读操作;相反, R2 应该可以与R1一起读数据,因为读不会修改数据,所以并行读取是安全的。 这是 第一个读者-作家的问题, 读者无需等候,当共享可以读时。 这也被称为 读者的偏好,其解决方案:

semaphore resource=1;
semaphore rmutex=1;
readcount=0;

/*
   resource.P() is equivalent to wait(resource)
   resource.V() is equivalent to signal(resource)
   rmutex.P() is equivalent to wait(rmutex)
   rmutex.V() is equivalent to signal(rmutex)
*/

writer() {
    resource.P();          //Lock the shared file for a writer

    <CRITICAL Section>
    // Writing is done

    <EXIT Section>
    resource.V();          //Release the shared file for use by other readers. Writers are allowed if there are no readers requesting it.
}

reader() {
    rmutex.P();           //Ensure that no other reader can execute the <Entry> section while you are in it
    <CRITICAL Section>
    readcount++;          //Indicate that you are a reader trying to enter the Critical Section
    if (readcount == 1)   //Checks if you are the first reader trying to enter CS
        resource.P();     //If you are the first reader, lock the resource from writers. Resource stays reserved for subsequent readers
    <EXIT CRITICAL Section>
    rmutex.V();           //Release

    // Do the Reading

    rmutex.P();           //Ensure that no other reader can execute the <Exit> section while you are in it
    <CRITICAL Section>
    readcount--;          //Indicate that you are no longer needing the shared resource. One fewer reader
    if (readcount == 0)   //Checks if you are the last (only) reader who is reading the shared file
        resource.V();     //If you are last reader, then you can unlock the resource. This makes it available to writers.
    <EXIT CRITICAL Section>
    rmutex.V();           //Release
}


[[Category:并发性]] [[Category:有未审阅翻译的页面]]

  1. ^ 引用错误:没有为名为courtois的参考文献提供内容
  2. ^ Taubenfeld, Gadi. Synchronization Algorithms and Concurrent Programming. Pearson Education. 2006: 301.