互斥锁 - 生产者,消费者模型

生产者,消费者模型
  • 锁的目的是为了让当前资源只能同时被一个线程操作
  • cond(条件变量)的作用是为了通知线程拿到锁,唤醒线程

MutexCond::MutexCond() {
    // 创建互斥锁
    mutex = SDL_CreateMutex();
    cond1 = SDL_CreateCond();
    // 创建条件变量
    cond2 = SDL_CreateCond();
    // 创建链表
    list = new std::__1::list<string>();
    
    // 创建消费者
    consume("消费者1");
    consume("消费者2");
    consume("消费者3");
    consume("消费者4");
    
    // 创建生产者
    produce("生产者1");
    produce("生产者2");
    produce("生产者3");
    produce("生产者4");
}

MutexCond::~MutexCond() {
    SDL_DestroyMutex(mutex);
    SDL_DestroyCond(cond1);
    SDL_DestroyCond(cond2);
}

void MutexCond::consume(string name) {
    thread([this, name]() {
        // 加锁
        SDL_LockMutex(mutex);
        while (true) {
            cout << name << "开始消费" << endl; //
            while (!list->empty()) {
                cout << "消费" << list->front() << endl;
                // 删除头部
                list->pop_front();
                // 睡眠500ms
                this_thread::sleep_for(chrono::milliseconds(500));
            }
            // 唤醒生产者:赶紧开始生产
            SDL_CondSignal(cond2);
            // 等待生产者生产
            SDL_CondWait(cond1, mutex);
        }
        // 解锁
        SDL_UnlockMutex(mutex);
        cout << "消费者解锁了" << endl;
    })
    .detach();
}

void MutexCond::produce(string name) {
    thread([this, name]() {
        SDL_LockMutex(mutex);
        while (true) {
            cout << name << "开始生产" << endl;
            list->push_back(to_string(++index));
            // 睡眠500ms
            this_thread::sleep_for(chrono::milliseconds(500));
            list->push_back(to_string(++index));
            this_thread::sleep_for(chrono::milliseconds(500));
            list->push_back(to_string(++index));
            this_thread::sleep_for(chrono::milliseconds(500));
            // 唤醒消费者:赶紧消费
            SDL_CondSignal(cond1);
            // 等待消费者
            SDL_CondWait(cond2, mutex);
        }
        SDL_UnlockMutex(mutex);
        cout << "生产者解锁了" << endl;
    })
    .detach();
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容