代码之家  ›  专栏  ›  技术社区  ›  ErniBrown

包含STD::线程的元素向量

  •  8
  • ErniBrown  · 技术社区  · 6 年前

    我要上课了 Tester 包含一个 std:thread 对象和 std::vector 属于 测试器 . 我知道我不能复制线程,所以 push_back 不可能,但为什么 emplace_back 不工作吗?我的密码副本在哪里?

    #include <iostream>
    #include <thread>
    #include <vector>
    #include <functional>
    #include <unistd.h>
    
    class Tester
    {
    public:
        Tester(std::function<void(void)> func) : 
            th(func)
        {
        }
    
        ~Tester()
        {
            th.join()
        }
    
    private:
        std::thread th;
    };
    
    std::vector<Tester> testers;
    
    void InnerHelloWorld()
    {
        std::cout << "Hello from the inner word!\n";
    }
    
    int main() {
        std::cout << "Hello World!\n";
    
        for(size_t i = 0 ; i < 4 ; i++)
        {
            testers.emplace_back(InnerHelloWorld);
        }
    
        sleep(1);
    
        return 0;
    }
    
    2 回复  |  直到 6 年前
        1
  •  15
  •   Mike Vine    6 年前

    th.join()
    

    Tester(Tester&&) = default;
    

    here

    Testers

    ~Tester()
     {
       if(th.joinable())
           th.join();
     }
    

    #include <iostream>
    #include <thread>
    #include <vector>
    #include <functional>
    
    #include <unistd.h>
    
    class Tester
    {
      public:
      Tester(std::function<void(void)> func) : 
        th(func)
      {
      }
    
      ~Tester()
      {
        if(th.joinable())
            th.join();
      }
    
      Tester(Tester&&) = default;
    
      private:
      std::thread th;
    };
    
    std::vector<Tester> testers;
    
    void InnerHelloWorld()
    {
      std::cout << "Hello from the inner word!\n";
    }
    
    int main() {
      std::cout << "Hello World!\n";
    
      for(size_t i = 0 ; i < 4 ; i++)
      {
        testers.emplace_back(InnerHelloWorld);
      }
    
      sleep(1);
    
      return 0;
    }
    
        2
  •  3
  •   user7860670    6 年前

    emplace

    Tester(Tester && other) : 
        th(::std::move(other.th))
    {
    }
    

    ~Tester()
    {
       if(th.joinable())
       {
           th.join();
       }
    }