C++

Parallel Tutorial 2: Shared Mutex (Implement with C++)

使用一般 mutex的case

#include <thread>
#include <mutex>
#include <chrono>
#include <array>


std::string Head[4] = {"Jason", "Astrid", "Tim", "Caspar"};
int currentHead = 0;
std::mutex editor;

void project_reader(const int id)
{
    for(int  i=0;i<10;i++)
    {
        editor.lock();
        printf("Reader-%d sees project head is %s\n", id, Head[currentHead].c_str());
        std::this_thread::sleep_for(std::chrono::microseconds(100));
        editor.unlock();
    }
}

void project_writer(const int id)
{
    for(int  i=0;i<10;i++)
    {
        editor.lock();
        currentHead = (currentHead+1)%4;
        printf("Writer-%d updated project head to %s\n", id, Head[currentHead].c_str());
        std::this_thread::sleep_for(std::chrono::microseconds(100));
        editor.unlock();
    }
}

int main()
{
    std::array<std::thread, 10> readers;
    for(unsigned int i = 0; i<readers.size(); i++)
        readers[i] = std::thread(project_reader, i);

    std::array<std::thread, 2> writers;
    for(unsigned int i = 0; i< writers.size();i++)
        writers[i] = std::thread(project_writer, i);

    for(unsigned int i =0;i<readers.size();i++)
        readers[i].join();
    for(unsigned int i=0;i<writers.size();i++)
        writers[i].join();
}

由圖片可以發現,一旦一個reader開始讀取,其他reader沒辦法一起讀取,必須要等到該thread unlock的時候才能讀取,但其實有一些狀況下,同時讀取是可以的,多個reader可以一起讀取,除非有人在進行writing.

使用Shared mutex的case:可以shared同時使用資源的不會互相lock,都可以同時讀取該資源。

// Shared Mutex
#include <thread>
#include <shared_mutex>
#include <chrono>
#include <array>

std::string Head[4] = {"Jason", "Astrid", "Tim", "Caspar"};
int currentHead = 0;
std::shared_mutex editor;

void project_reader(const int id)
{
    for(int  i=0;i<10;i++)
    {
        editor.lock_shared();
        printf("Reader-%d sees project head is %s\n", id, Head[currentHead].c_str());
        std::this_thread::sleep_for(std::chrono::microseconds(100));
        editor.unlock_shared();
    }
}

void project_writer(const int id)
{
    for(int  i=0;i<10;i++)
    {
        editor.lock();
        currentHead = (currentHead+1)%4;
        printf("Writer-%d updated project head to %s\n", id, Head[currentHead].c_str());
        std::this_thread::sleep_for(std::chrono::microseconds(100));
        editor.unlock();
    }
}

int main()
{
    std::array<std::thread, 10> readers;
    for(unsigned int i = 0; i<readers.size(); i++)
        readers[i] = std::thread(project_reader, i);

    std::array<std::thread, 2> writers;
    for(unsigned int i = 0; i< writers.size();i++)
        writers[i] = std::thread(project_writer, i);

    for(unsigned int i =0;i<readers.size();i++)
        readers[i].join();
    for(unsigned int i=0;i<writers.size();i++)
        writers[i].join();
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *