【发布时间】:2020-04-04 00:19:03
【问题描述】:
有没有办法使用 C++11 线程生成一个可以以某种方式访问类成员的线程?
假设我像这样实例化一个对象,
FITS_file <float> fits_file;
类在头文件中定义为:
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
}
工作线程 (write_image_thread) 必须是静态的,但如果它是静态的,则我无法访问线程内的 this-> 成员。
我尝试像这样生成线程:
std::thread([&](){this->write_image_thread(array, info);}).detach();
但是 (a) 我不知道这是否正确(即使它可以编译); (b) 我似乎在传递给线程的内容方面受到限制; (c) 我仍然无法访问this-> 成员。
我知道如果我使用 Boost 线程,我可以做我想做的事,也许我只需要这样做,但我想知道是否有办法从这里直接使用 C++11。
【问题讨论】:
-
您是否尝试过让
write_image_thread成为常规类方法,而不是静态线程函数,并且它们只是调用std::thread(&FITS_file<T>, this);,而write_image_thread像任何其他类方法一样正常访问其成员?请注意,您有责任(以某种方式)确保对象在线程终止之前一直存在。 -
添加到 Sam:确保(以某种方式)对象在线程终止之前一直存在为此,我将删除
detach()并制作 @ 987654330@班级成员。然后析构函数可以检查线程是否有joinable()和join()线程以防万一。 -
@SamVarshavchik 我认为这就是答案...查看我提出的完整答案。
标签: c++ multithreading class c++11 static