【问题标题】:Using mutex and conditional variable instead of semaphore to print numbers from 1 to 10 in c++14?使用互斥锁和条件变量而不是信号量在 c++14 中打印从 1 到 10 的数字?
【发布时间】:2015-10-18 23:09:45
【问题描述】:

我正在尝试使用两个线程打印从 1 到 n 的数字。一个用于递增,另一个用于打印。由于新 c++ 中没有标准库信号量类,因此我使用互斥锁和条件变量来模拟二进制信号量来完成这项工作。下面的代码不打印任何值,但“main is here!”。我检查了我的代码几次,但找不到解决方案。我在这里错过了什么吗?

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;

mutex m;
condition_variable cv;
int v=0;

void modify()
{
    while(v<10)
    {
        lock_guard<mutex> lock(m);
        v=v+1;

        cv.notify_all();
    }
}

void print()
{
    while(v<10)
    {
        unique_lock<mutex> lock(m);
        cv.wait(lock);
        cout<<v<<" ";
        lock.unlock();
        cv.notify_all();
    }
}

int main() {
    thread t1(modify);
    thread t2(print);

    t1.join();
    t2.join();

    cout<<endl<<"main is here!"<<endl;

    return 0;
}

【问题讨论】:

    标签: multithreading mutex semaphore c++14


    【解决方案1】:

    信号量的实现非常简单,可以在这里找到: C++0x has no semaphores? How to synchronize threads?

    但实际上你并不需要它

    您的代码的问题是modify 函数不等待print 函数。查看我对代码的更改:

    void modify()
    {
        // Fix #1: Any access to v should be done inside lock
        unique_lock<mutex> lock(m);
    
        while(v<10)
        {
            v=v+1;
            cv.notify_all();
    
            // Fix #2: wait for print function
            cv.wait(lock);
        }
    }
    
    void print()
    {
        // See Fix #1
        unique_lock<mutex> lock(m);
    
        while(v<10)
        {
            cv.wait(lock);
            cout << v << " ";
            // Fix #3: no need to unlock here
            cv.notify_all();
        }
    }
    

    【讨论】:

    • 感谢您的更新。我实施了您的更改,但仍然没有打印任何内容。我使用coliru.stacked-crooked.com 的在线编译器和命令 g++ -std=c++14 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
    猜你喜欢
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2010-11-06
    • 1970-01-01
    • 2011-10-11
    • 2021-10-21
    相关资源
    最近更新 更多