Start thread within member function using std::thread & std::bind

bee*_*hnu 0 c++ multithreading c++11

I have few queries with respect to below code snapshot.

1) With respect to pthread_create(), assume Thread_1 creates Thread_2. To my understanding Thread_1 can exit without join, but still Thread_2 will keep running. Where as in below example without join() I am not able to run thread and I am seeing exceptions.

2) In few examples I am seeing thread creation without thread object as below. But when I do the same, code is terminated.

std::thread(&Task::executeThread, this);

I am compiling with below command.
g++ filename.cpp -std=c++11 -lpthread
Run Code Online (Sandbox Code Playgroud)

But still it terminate with exception. Is this right way of creating thread or is there any different version of C++ (In my project already they are compiling but not sure about the version).

3)在我的项目代码的一些示例中,我看到了以下创建线程的方法。但是我无法使用以下示例执行。

std::thread( std::bind(&Task::executeThread, this) );
Run Code Online (Sandbox Code Playgroud)

下面是我的代码快照。

#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;
}
Run Code Online (Sandbox Code Playgroud)

感谢和问候

毗湿奴比玛

Max*_*kin 5

std::thread(&Task::executeThread, this);语句创建并销毁线程对象。未连接或分离线程时(如您的语句中)调用的析构函数std::threadstd::terminate

没有充分的理由std::bind在C ++ 11中使用,因为在空间和速度方面,lambda更好。

构建多线程代码时,需要-pthread在编译和链接时都指定选项。链接器选项-lpthread既不足又不必要。