你能初始化一个类中引用该类中函数的线程吗
Can you initialize a thread in a class which references a function inside that class?
我有以下代码,它不是使用编译的
clang++ -std=c++11 -pthread threaded_class.cpp -o test
和
#include <iostream>
#include <thread>
class Threaded_Class {
public:
Threaded_Class();
void init();
};
Threaded_Class::Threaded_Class() {
std::thread t1(init);
t1.join();
}
void Threaded_Class::init() {
std::cout << "Hello, world" << std::endl;
}
int main() {
Threaded_Class a;
return 0;
}
我收到了以下编译器错误,这些错误似乎有点模糊
threaded_class.cpp:13:20: error: reference to non-static member function must be
called; did you mean to call it with no arguments?
std::thread t1(init);
^~~~
()
threaded_class.cpp:13:17: error: no matching constructor for initialization of
'std::thread'
std::thread t1(init);
^ ~~~~~~
以这种方式初始化线程合法吗?
另一种方法是使用std::bind
#include <functional>
# instead of std::thread t1(init);
std::thread t1(std::bind(&Threaded_Class::init,this));
这提供了类实例。
因为函数是非静态的,所以线程没有类实例来调用该方法。为此,您可以创建一个静态函数,将您的调用转发到init:
class Threaded_Class {
public:
Threaded_Class();
void init();
static void static_init(Threaded_Class * instance)
{
instance->init();
}
};
Threaded_Class::Threaded_Class() {
std::thread t1(static_init,this);//new line
t1.join();
}
相关文章:
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- condition_variable、引用和线程:谁拥有锁?
- 启动类函数作为失去引用的线程
- 将常量引用传递给线程
- 线程安全的引用计数队列C++
- 具有对象的右值引用的线程
- C++11 多线程,通过引用传递
- C++ 线程函数通过引用传递
- C 11线程汇编错误传递字符串作为复制的引用
- C++ 11 您可以通过不同线程中的引用安全地传递和访问 std::atomics 吗?
- 通过引用将变量传递给多个线程会损坏堆
- 线程函数中的通用引用
- 通过引用和多线程传递对象
- 如何在类中进行 c++ 多线程处理(将线程引用保留为成员 var)
- 为线程构造函数传递引用以将其绑定到函数失败
- 通过在引用线程对象来传递取消引用的“this”指针来在函数对象构造函数中创建线程是好是坏
- 对抽象类的引用不能传递给线程函数?
- std::线程传递向量元素(按引用)
- 取消引用指向不同线程中的原子对象的只读非原子指针是否安全
- 引用计数类和多线程