在类中使用std :: mutex作为成员变量 [英] Using std::mutex as member variable in a class

查看:1575
本文介绍了在类中使用std :: mutex作为成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了一个以std::mutex my_mutex作为其私有成员变量的类.但是,当我尝试在不同线程调用的成员函数中使用lock_guard来使用它时,编译器会抛出很多错误.如果我将此互斥锁保留在课堂之外,那么它将起作用.代码如下

I have defined a class that has std::mutex my_mutex as its private member variable. But when I try to use it using lock_guard in a member function which is called from different threads, the compiler throws up a lots of errors. If I keep this mutex outside the class it works. The code is as follows

class ThreadClass
{
  std::mutex my_mutex;
  public: 
     void addToList(int max, int interval)
    {

      std::lock_guard<std::mutex> guard(my_mutex);
      for (int i = 0; i < max; i++) 
       {
            // Some operation
       }
    }
};


 int main()
 {
    std::thread ct(&ThreadClass::addToList,ThreadClass(),100,1);
    std::thread ct2(&ThreadClass::addToList,ThreadClass(),100,10);
    std::thread ct3(&ThreadClass::print,ThreadClass());

     ct.join();
     ct2.join();
     ct3.join();
  }

如果将同一个my_mutex保留在类之外,则可以正常工作.因此,当同一个变量在类中并在线程作用于成员函数中调用时,它是否像静态成员一样对待?

If the same my_mutex is kept out of the class then it works fine. So when the same variable is within the class and called within the member function acted on by a thread, does it treat like a static member?

推荐答案

std::thread构造函数复制传递给执行函数的参数.但是std::mutex是不可复制的,因此ThreadClass如果具有这样的成员,则是不可复制的.

The std::thread constructor copies the arguments that are passed to the executed function. But std::mutex is non-copyable and so ThreadClass is non-copyable if it has such a member.

您要将一个临时ThreadClass对象传递给std::thread,但是您可能想在所有线程中使用同一对象.您可以使用std::ref传递现有对象的引用.以下代码可在GCC 7.1.0上编译:

You are passing a temporary ThreadClass object to std::thread, but you probably want to use the same object in all your threads. You can use std::ref to pass a reference of an existing object. The following code compiles on GCC 7.1.0:

#include <thread>
#include <mutex>

class ThreadClass
{
    std::mutex my_mutex;
public: 
    void addToList(int max, int interval)
    {
        std::lock_guard<std::mutex> guard(my_mutex);
        // ...
    }
    void print()
    {
        // ...
    }
};

int main()
{
    ThreadClass obj;
    std::thread ct(&ThreadClass::addToList, std::ref(obj), 100, 1);
    std::thread ct2(&ThreadClass::addToList, std::ref(obj), 100, 10);
    std::thread ct3(&ThreadClass::print, std::ref(obj));

    ct.join();
    ct2.join();
    ct3.join();
}

将指针传递给对象而不是引用也应该起作用:

Passing a pointer to the object instead of a reference should also work:

std::thread ct(&ThreadClass::addToList, &obj, 100, 1);

这篇关于在类中使用std :: mutex作为成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆