【发布时间】:2019-10-07 10:17:19
【问题描述】:
我对以下代码快照的查询很少。
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( std::bind(&Task::executeThread, this) );的一种用法吗?目前您对我们看不到的其他代码的引用有点令人困惑 -
你应该几乎总是加入线程。一个例外是当您愿意在其他线程仍在运行时退出程序,从而有效地杀死它们。
-
在您的情况下,“Thread_1”是主线程。
所有线程都属于/由进程管理。如果主线程退出,则进程终止。所以,这就是你无法运行并看到异常的原因。
标签: c++ multithreading c++11