【问题标题】:How to fix "use of deleted function" when using mutex and condition variable as member?使用互斥锁和条件变量作为成员时如何修复“使用已删除函数”?
【发布时间】:2019-10-15 01:27:15
【问题描述】:

我正在做一些多线程练习,但无法获得此代码传递编译。我在网上搜索,但目前还不确定原因。

#include <condition_variable>
#include <functional>
#include <iostream>
#include <mutex>
#include <thread>

using namespace std;

class FooBar {
  private:
    int n;

  public:
    FooBar(int n) {
        this->n = n;
    }

    void foo(function<void()> printFoo) {
        for (int i = 0; i < n; i++) {
            printFoo();
        }
    }

    std::mutex foo_mtx;
    std::condition_variable foo_cv;
};

void printFoo()
{
    cout << "foo";
}

int main ()
{
    FooBar foobar(10);
    std::thread foo_thread = std::thread(&FooBar::foo, foobar, printFoo);
    foo_thread.join();
    return 0;
}

如果我不添加互斥体和条件变量,这段代码编译运行良好。

error: use of deleted function ‘FooBar::FooBar(const FooBar&)’
error: use of deleted function ‘std::mutex::mutex(const std::mutex&)’
error: use of deleted function ‘std::condition_variable::condition_variable(const std::condition_variable&)’

【问题讨论】:

    标签: c++ mutex condition-variable


    【解决方案1】:

    您正在复制fooBar。编译器说你是不允许的。不允许您这样做,因为无法复制互斥锁。

    std::thread foo_thread = std::thread(&FooBar::foo, std::ref(foobar), printFoo);
    

    这将使特定的编译器错误消失。如果不构建它,我无法确定没有其他问题。

    std::thread foo_thread = std::thread([&foobar]{ foobar.foo(printFoo); });
    

    这是解决同一问题的更明智的方法。与使用基于 INVOKE 的接口相比,Lambda 通常是一个更好的计划。

    【讨论】:

    • @NadavB OP 的代码复制了一个互斥锁。你不能那样做。我的代码没有复制互斥锁。所以我没有得到 OP 的错误。不做导致错误的事情会导致没有错误。如前所述,我不保证我的代码有效——我不知道 OP 的代码在什么上下文中。不复制该互斥锁可能会导致其他问题。我只是指出了导致 OP 问题的原因。
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多