Search code examples
c++atomicstl-algorithm

std::generate_n algorithm requires copying ctor. how to avoid this in code below?


    std::vector<std::thread> thread_pool;
    ...
    std::generate_n(std::back_inserter(thread_pool), cpu_cores,
                    [] (){
        //...
        return std::thread{worker(worker_name) };
    } );

where:

  class worker {
      std::atomic_bool done;
  protected:
      void operator()() {
          while(!done) {
 //   some work
          }
   }
   public:
   worker(const std::string& worker_name)
       : done(false) {
        // some initialization 
    }
 // other fields
 };


  error: use of deleted function 'std::atomic_bool::atomic_bool(const std::atomic_bool&)'

GCC 4.9

as I see atomic can't be copied, just moved. code above requires copying ctor for some_object class. how to solve this ?

(probably the design itself is worse, here , some_object is a functor for a thread, and atomic is a flag to shut the process down)


Solution

  • Your class:

    class worker {
        std::atomic_bool done;
    };
    

    is not copyable or moveable because std::atomic explicitly deletes its copy constructor (which implicitly deletes its move constructor). If you want to allow it to be moved or copied, you have to write that yourself, e.g.:

    worker(worker&& rhs)
    : done(rhs.done.load())
    { }