c++ - 使用互斥锁和条件变量作为成员时如何修复 "use of deleted function"?

标签 c++ mutex condition-variable

我正在做一些多线程练习,但无法让这段代码通过编译。我在网上搜索,但到目前为止还不确定原因。

#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&)’

最佳答案

您正在复制一个 fooBar。编译器说你不被允许。不允许您这样做,因为无法复制互斥量。

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

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

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

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

关于c++ - 使用互斥锁和条件变量作为成员时如何修复 "use of deleted function"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58386020/

相关文章:

c - 打破条件变量死锁

c++ - 0 作为 std::condition_variable::wait_for 中的超时

c++ - 如何使用 2 个主要 src 文件构建 cmake 项目

c++ - 在循环中从 unordered_map 中删除元素

c++ - Effective C++ Item 43 了解如何访问模板化基类中的名称

objective-c - 在 objective-c 中使用 @synchronized 指令的死锁和活锁问题

linux - 如何检查 pthread_mutex 是否基于健壮的 futex

go - sync.Mutex 或 http.HandleFunc 不工作

C程序不允许超过n个线程同时执行函数f

c++ - Arduino 将字符串拆分为带分隔符的数组