Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux 多線程經典題:讀者寫者問題

讀者寫者問題同樣是面試與教材中的常客。

題目大意:有一個寫者與許多讀者,多個讀者可以同時讀取檔案,但寫者在寫入時不允許有任何讀者在讀;同樣地,有讀者正在讀時,寫者也不能寫。

程式碼

// reader_writer.cpp
//////////////////////////////////////////////////////////////////////
// 讀者寫者問題
// 有一個寫者很多讀者,多個讀者可以同時讀文件,但寫者在寫文件時不允許有讀者在讀文件,
// 同樣有讀者讀時寫者也不能寫。
//////////////////////////////////////////////////////////////////////

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

// 定義數據類
class data
{
public:
    data(int i, float f):
        I(i), F(f)
    {}

    int I;
    float F;
};

// 讀者寫者讀寫的內容
data *p_data = NULL;

pthread_rwlock_t lock;

// 寫者數目
const int WRITER_NUMBER = 2;

void *reader(void *arg);
void *writer(void *arg);

int main(int argc, char **argv)
{
    pthread_t reader_tid;
    pthread_t writer_tid[WRITER_NUMBER];

    pthread_create(&reader_tid, NULL, reader, NULL);
    for (int i = 0; i < WRITER_NUMBER; ++i)
    {
        pthread_create(&writer_tid[i], NULL, writer, (void *) i);
    }

    sleep(1);

    return 0;
}

void *reader(void *arg)
{
    int id = (int) arg;

    pthread_detach(pthread_self());

    while (true)
    {
        pthread_rwlock_rdlock(&lock);
        printf("reader %d is reading the data; ", id);
        if (p_data == NULL)
        {
            printf("the data is NULL\n");
        }
        else
        {
            printf("the data is (%d, %f)\n", p_data->I, p_data->F);
        }
        pthread_rwlock_unlock(&lock);
    }

    return (void *) 0;
}

void *writer(void *arg)
{
    pthread_detach(pthread_self());

    while (true)
    {
        pthread_rwlock_wrlock(&lock);
        printf("writer is writing the data; ");
        if (p_data == NULL)
        {
            p_data = new data(1, 1.1f);
            printf("writer create the data (%d, %f)\n", p_data->I, p_data->F);
        }
        else
        {
            delete p_data;
            p_data = NULL;
            printf("writer free the data\n");
        }
        pthread_rwlock_unlock(&lock);
    }

    return (void *) 0;
}

為什麼用 pthread_rwlock_t

這個題目最漂亮的解法就是直接使用 POSIX 提供的讀寫鎖。pthread_rwlock_rdlock() 允許多個讀者同時持有鎖,而 pthread_rwlock_wrlock() 則是排他鎖,一旦寫者取得,所有讀者與其他寫者都必須等待。

換句話說,「多讀共享、寫入獨佔」這條規則完全由函式庫實作,我們不必自己維護讀者計數器與狀態機,也不必手忙腳亂地處理飢餓與死鎖。這正是工程實務上的正確取捨:能用標準機制的時候,不要自己造輪子。

若題目進一步要求「寫者优先」或「讀者优先」,才需要退回自行以 mutex 加 condition 實作,並明確定義排隊規則。

Copyright © Linux教程網 All Rights Reserved