如何从main()调用线程成员函数
how to call a thread member function from main ( )
在编译使用线程的程序时出现错误。这是引起问题的部分。如果有人告诉我是否以正确的方式调用线程函数,那就太好了。
在main.cpp:int main()
{
WishList w;
boost::thread thrd(&w.show_list);
thrd.join();
}
在another_file.cpp: class WishList{
public:
void show_list();
}
void WishList::show_list(){
.
.
.
.
}
我得到以下错误
error: ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say ‘&WishList::show_list’
/home/sharatds/Downloads/boost_1_46_1/boost/thread/detail/thread.hpp: In member function ‘void boost::detail::thread_data<F>::run() [with F = void (WishList::*)()]’:
/home/sharatds/Downloads/boost_1_46_1/boost/thread/detail/thread.hpp:61:17: error: must use ‘.*’ or ‘->*’ to call pointer-to-member function in ‘((boost::detail::thread_data<void (WishList::*)()>*)this)->boost::detail::thread_data<void (WishList::*)()>::f (...)’, e.g. ‘(... ->* ((boost::detail::thread_data<void (WishList::*)()>*)this)->boost::detail::thread_data<void (WishList::*)()>::f) (...)’
编辑:在为线程安装Boost库时遇到问题。我应该尽快试一下
获取成员函数地址的语法是&ClassName::FunctionName
,所以应该是&WishList::show_list
,但是现在需要一个对象来调用函数指针。最好的(也是最简单的)是使用boost::bind
:
#include <boost/bind.hpp>
WishList w;
boost::thread t(boost::bind(&WishList::show_list, &w));
与线程无关,这只是"如何获得指向成员函数的指针"。按编译器说的做,说&WishList::show_list
。但是您可能还需要传递实例指针。
更新:是的,使用bind
就像Xeo说的。
关于你的标题:注意函数不"属于线程"。类不是线程的一部分。所有线程都访问相同的内存——每个线程都有自己的自动存储空间,但是在类定义中没有任何内容说"这将在单独的线程中"。
相关文章:
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在另一个线程中调用luaL_error会引发qWarning
- 以线程安全的方式调用"QQuickPaintedItem::updateImage(const QImage&image)"(no QThread)
- 如何从线程中的不同模块调用函数?
- 如何在调用析构函数时优雅地停止/销毁带有阻塞调用C++线程?
- 如何声明由多个线程调用的 C++ DLL 的内部类,而无需导出类
- 是否可以创建一个从不同类调用函数的线程?
- 为什么即使调用了析构函数,C++11 中的分离线程也可以执行
- 非静态成员失败的线程调用函数
- 线程调用的函数对对象删除是否安全?
- 将类成员函数作为线程调用到另一个类成员函数时发出警告消息
- 通过 Qt 中的线程调用 Rust 库
- Qt信号和插槽如果从QRunnable或其他线程调用,则不起作用
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 由并发无序映射查找线程调用的函数是否安全?
- 每个线程 C++ 保护以防止重入函数调用
- localtime() 函数正在调用 ___lll_lock_wait_private(),这会使线程陷入死锁
- 当我在C++中调用 struce 的只读静态成员时,线程是否安全
- 线程 std::调用未知类型,无法专门化函数错误
- 工作线程一直在等待,condition_variable甚至调用了notify_all