操作系统同步互斥经典问题——读者写者问题

2014/10/17 23:34
阅读数 38

读者优先

#include <iostream>
#include <mutex>
#include <thread>

using namespace std;

mutex mt, wsem;
int readcount = 0;
#define READ(a) cout << a << " is reading..." << endl;
#define FINISH(a) cout << a << " finished reading." << endl;
#define WRITE cout << "writing..." << endl;

void P(mutex &mt)
{
    mt.lock();
}

void V(mutex &mt)
{
    mt.unlock();
}

// 加入unistd.h出现问题,似乎与thread的兼容性比较差,于是重写
void delay()
{
    int sum=0;
    for(int i = 0; i < 10000000; i++)
        sum += i
}

void read(string a)
{
    for(int i = 0; i < 3; i++)
    {
        P(mt);
        readcount++;
        if(readcount == 1)
            P(wsem);
        V(mt);
        READ(a);
        delay();
        P(mt);
        readcount--;
        FINISH(a);
        if(readcount == 0)
            V(wsem);
        V(mt);
    }
}

void write()
{
    for(int i = 0; i < 5; i++)
    {
        P(wsem);
        WRITE;
        delay();
        V(wsem);
    }
}

int main()
{
    thread reader1(read, "svtter");
    thread reader2(read, "sr");
    thread reader3(read, "yym");
    thread reader4(read, "xiaoniu");
    thread writer(write);

    reader1.join();
    reader2.join();
    reader3.join();
    reader4.join();
    writer.join();

    return 0;
}

写者优先

使rsem中只有一个读者在等待,保证了如果有写者,写者优先写。

#include <iostream>
#include <mutex>
#include <thread>

using namespace std;

#define READ(a,i) cout << a << i<<" is reading..." << endl;
#define FINR(a,i) cout << a << i<<" finished reading." << endl;
#define WRITE(a,i) cout << a <<i<<" is writing..." << endl;
#define FINW(a, i) cout << a <<i<<" finished writing..." << endl;

void P(mutex &mt)
{
    mt.lock();
}

void V(mutex &mt)
{
    mt.unlock();
}

// 加入unistd.h出现问题,似乎与thread的兼容性比较差,于是重写
void delay()
{
    int sum=0;
    for(int i = 0; i < 10000000; i++)
        sum += i;
}


mutex mr, wsem, rsem, mrc, mwc;
int readcount = 0;
int writecount = 0;

void read(string a)
{
    for(int i = 0; i < 5; i++)
    {
        P(mr);
        P(rsem);
        P(mrc);
        readcount++;
        if(readcount == 1)
            P(wsem);
        V(mrc);
        V(rsem);
        V(mr);
        READ(a, i);
        P(mrc);
        FINR(a, i);
        readcount--;
        if(readcount == 0)
            V(wsem);
        V(mrc);
    }
}

void write(string a)
{
    for(int i = 0; i < 3; i++)
    {
        P(mwc);
        writecount++;
        if(writecount == 1)
            P(rsem);
        V(mwc);
        P(wsem);
        WRITE(a, i);
        FINW(a, i);
        V(wsem);
        P(mwc);
        writecount--;
        if(writecount == 0)
            V(rsem);
        V(mwc);
    }
}

int main()
{
    thread reader1(read, "svtter");
    thread writer1(write, "sr");
    thread writer2(write, "zs");
    thread writer3(write, "yym");

    reader1.join();
    writer1.join();
    writer2.join();
    writer3.join();

    return 0;
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部