繁体   English   中英

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

[英]Multithreading with templated class member function

所以,我对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”的行导致编译器告诉我:

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))...));
                            ^~~~~~~~~~~~

现在,我在编写代码时已经看过这个问题和这个问题 ,但我仍然缺少一些小细节。 如果有人可以提供一些帮助,那就太棒了。 谢谢!

thread需要复制其所有参数,并且您的Container不可复制。 它是不可复制的,因为它的一个成员( std::mutex )是不可复制的。 对此的解决方案不是直接给thread c给它一些它可以复制的东西。

那是:

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

以下应该也可以,但可能不会(参见TC的评论 ):

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM