c++ - 具有模板化类成员函数的多线程

标签 c++ multithreading c++11

所以,我对 STL 提供的 C++11 并发编程功能还很陌生,我正在研究以下代码:

    #include <iostream>
    #include <thread>
    #include <mutex>
    #include <list>

    using namespace std;

    template <typename T>
    class Container
    {
        private:
            mutex mu;
            list<T> myList;

        public:
            void add(T element)
            {
                lock_guard<mutex> lock1(mu);
                myList.emplace_back(element);
            }
            void remove()
            {
                lock_guard<mutex>lock2(mu);
                myList.pop_back();
            }
            void print()
            {
                for(const auto & element : myList)
                {
                    cout << element << endl;
                }
            }
    };

    int main()
    {
        Container<int> c;

        thread t1(&Container<int>::add, c, 5); //ERROR
        thread t2(&Container<int>::add, c, 10); //ERROR

        thread t4(&Container<int>::remove, c); //ERROR
        thread t5(&Container<int>::remove, c); //ERROR

        t1.join();
        t2.join();
        t4.join();
        t5.join();

        c.print();
    }

当我尝试编译我的代码时,我标记为“错误”的行导致编译器告诉我:

error: call to implicitly-deleted copy constructor of
  'typename decay<Container<int> &>::type' (aka 'Container<int>')
return _VSTD::forward<_Tp>(__t);

error: no matching constructor for initialization of
  '__tuple_leaf<1UL, Container<int> >'
        __tuple_leaf<_Uf, _Tf>(_VSTD::forward<_Up>(__u))...,

error: no matching function for call to '__decay_copy'
                            __decay_copy(_VSTD::forward<_Args>(__args))...));
                            ^~~~~~~~~~~~

现在,我查看了这个 question还有这个 question虽然我正在编写代码,但我仍然缺少一些小细节。如果有人可以提供一些帮助,那就太好了。谢谢!

最佳答案

thread 需要复制其所有参数,而您的Container 是不可复制的。它是不可复制的,因为它的成员之一(std::mutex)是不可复制的。解决这个问题的方法不是直接给 thread c 而是给它一些它可以复制的东西。

即:

    thread t1(&Container<int>::add, &c, 5);

以下内容也应该有效,但可能无效(参见 T.C.'s comment):

    thread t2(&Container<int>::add, std::ref(c), 10);

请注意,这没有为您编译是件好事,因为否则您的线程将在您的容器的多个拷贝上执行工作 - 而不仅仅是您可能期望的那个。

关于c++ - 具有模板化类成员函数的多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30294593/

相关文章:

c++ - "separately compiled C++ templates"是什么?

r - 排列 : Speed up, 预测和/或多线程

c++ - 连接 vector 的 Constexpr 函数

c++ - 通用 lambda 与标准模板函数(使用什么以及何时使用)

c++ - 使用 CMake 将错误与静态方法链接起来

c++ - 如何在 64 位(而不是任何 80 位寄存器)中强制所有 double

c# - 使用 .AsParallel().ForAll 或 Parallel.ForEach 性能问题并行化任务

java - 澄清处理数千个日志文件的线程性能

c++ - 如何检查成员运算符(类型)?

c# - 是否允许使用任何随机 DLL 文件作为库?