c++ - 使用 std::thread 和 std::bind 在成员函数中启动线程
问题描述
我对下面的代码快照几乎没有疑问。
1) 关于 pthread_create(),假设 Thread_1 创建 Thread_2。据我了解,Thread_1 可以在不加入的情况下退出,但 Thread_2 仍将继续运行。在下面没有 join() 的示例中,我无法运行线程并且我看到异常。
2)在几个例子中,我看到没有线程对象的线程创建如下。但是当我这样做时,代码被终止。
std::thread(&Task::executeThread, this);
I am compiling with below command.
g++ filename.cpp -std=c++11 -lpthread
但它仍然异常终止。这是创建线程的正确方法还是有任何不同版本的 C++(在我的项目中他们已经在编译但不确定版本)。
3)在我的项目代码的几个示例中,我看到了以下创建线程的方式。但我无法使用下面的示例执行。
std::thread( std::bind(&Task::executeThread, this) );
下面是我的代码快照。
#include <iostream>
#include <thread>
class Task
{
public:
void executeThread(void)
{
for(int i = 0; i < 5; i++)
{
std::cout << " :: " << i << std::endl;
}
}
void startThread(void);
};
void Task::startThread(void)
{
std::cout << "\nthis: " << this << std::endl;
#if 1
std::thread th(&Task::executeThread, this);
th.join(); // Without this join() or while(1) loop, thread will terminate
//while(1);
#elif 0
std::thread(&Task::executeThread, this); // Thread creation without thread object
#else
std::thread( std::bind(&Task::executeThread, this) );
while(1);
#endif
}
int main()
{
Task* taskPtr = new Task();
std::cout << "\ntaskPtr: " << taskPtr << std::endl;
taskPtr->startThread();
delete taskPtr;
return 0;
}
感谢和问候
毗湿奴比玛
解决方案
std::thread(&Task::executeThread, this);
语句创建和销毁一个线程对象。当线程未加入或分离时调用的析构函数(如您的语句中)。std::thread
std::terminate
没有充分的理由std::bind
在 C++11 中使用,因为 lambda 在空间和速度方面更好。
在构建多线程代码时,您需要-pthread
在编译和链接时指定选项。链接器选项-lpthread
既不充分又不必要。
推荐阅读
- azure - 如何将 powershell 脚本传递给 VM?转义 \ 似乎不起作用
- assembly - 如何定义一个20字节的字符串
- loops - 填充交叉销售模板的循环功能
- c# - 创建该类的对象时是否调用该类的主函数?
- r - 用“pivottabler”包中的字符替换缺失值
- javascript - 有没有办法像事件监听器一样在浏览器中查看 setInterval 行为?
- php - PECL PCSC 安装在 PHP 7.4 上
- javascript - 如何使每个条形图成为 D3 中的图像?
- java - Spring BOOT 中带有 REST 的 Angular
- cakephp - 在 Digitalocean 中找不到 CakePHP 目录