Is there a way, using C++11 threads, to spawn a thread which can somehow access class members?
Let's say I instantiate an object like this,
FITS_file <float> fits_file;
where the class is defined in a header file as:
template <class T>
class FITS_file {
private:
std::mutex fits_mutex; //!< used to block writing_file semaphore in multiple threads
bool writing_file; //!< semaphore indicates file is being written
std::unique_ptr<CCfits::FITS> pFits; //!< pointer to FITS data container
public:
FITS_file() {
this->writing_file = false;
};
long write_image(T* data, Archon::Information& info) {
std::thread(write_image_thread, array, info).detach(); // spawn thread here
return 0;
}
static void write_image_thread(std::valarray<T> &data, Archon::Information &info) {
// lock mutex, set writing_file=true, does the work, set writing_file=false
// must be static (?) for C++ threads
// but can't access this->fits_mutex and friends because it's static
}
The worker thread (write_image_thread) has to be static but if it's static then I can't access this->
members inside the thread.
I tried spawning the thread like this:
std::thread([&](){this->write_image_thread(array, info);}).detach();
but (a) I don't know if that's right (even though it compiles); and (b) I seem to be limited in what I can pass to the thread; and (c) I still can't access this->
members.
I understand I can do what I want if I use Boost threads, and maybe I just have to do that, but I was wondering if there was a way there from here using straight C++11.
Aucun commentaire:
Enregistrer un commentaire