首页 > 解决方案 > 使用 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;
}

感谢和问候

毗湿奴比玛

标签: c++multithreadingc++11

解决方案


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

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

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


推荐阅读