0
点赞
收藏
分享

微信扫一扫

C++多线程读写问题

互联网码农 2022-02-07 阅读 60

C++多线程读写问题

#include <iostream>
#include <thread>
#include <mutex>
#include <unistd.h>
using namespace std;

mutex read_write_mutex;

void read_handler()
{
    while(true)
    {
        read_write_mutex.lock();
        cout << "A" << endl;
        read_write_mutex.unlock();
        sleep(2);
    }
}

void write_handler()
{
    while(true)
    {
        read_write_mutex.lock();
        cout << "B" << endl;
        read_write_mutex.unlock();
        sleep(2);
    }
}

int main()
{
    thread read_thread(read_handler);
    thread write_thread(write_handler);

    read_thread.join();
    write_thread.join();

    return 0;
}
举报

相关推荐

0 条评论