C ++ std :: thread的成员函数 [英] C++ std::thread of a member function

查看:779
本文介绍了C ++ std :: thread的成员函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编程一个命令行服务器,它将从串行端口接收信息,解析它,并将其记录在内部对象中。

I'm trying to program a command line server that would receive information from a serial port, parse it, and record it in an internal object.

请求从客户端服务器将返回请求的信息。

Then upon request from a client the server would return the requested information.

我想要做的是将接收器&解析器部分在一个单独的线程中,以使服务器一起运行,而不干扰数据收集。

What I want to do is put the receiver & parser parts in a separated thread in order to have the server running along side, not interfering with the data collection.

#include <iostream>
#include <thread>

class exampleClass{
    std::thread *processThread;

    public void completeProcess(){
        while(1){
            processStep1();
            if (verification()){processStep2()}
        }
    };

    void processStep1(){...};
    void processStep2(){...};
    bool verification(){...};
    void runThreaded();
} // End example class definition

// The idea being that this thread runs independently
// until I call the object's destructor

exampleClass::runThreaded(){
    std::thread processThread(&exampleClass::completeProcess, this);
} // Unfortunately The program ends up crashing here with CIGARET


推荐答案

您正在成员函数中运行本地线程。你必须加入它或分离它,因为它是本地的,你必须在函数本身这样做:

You are running a local thread inside a member function. You have to join it or detach it and, since it is local, you have to do this in the function itself:

exampleClass::runThreaded()
{
    std::thread processThread(&exampleClass::completeProcess, this);
    // more stuff
    processThread.join();
} //



我猜你真正想要的是启动一个数据成员线程而不是启动一个本地的。如果你这样做,你仍然必须在某处加入它,例如在析构函数中。在这种情况下,您的方法应该是

I am guessing what you really want is to launch a data member thread instead of launching a local one. If you do this, you still have to join it somewhere, for example in the destructor. In this case, your method should be

exampleClass::runThreaded()
{
    processThread = std::thread(&exampleClass::completeProcess, this);
}

和析构函数

exampleClass::~exampleClass()
{
    processThread.join();
}

processThread 是一个 std :: thread ,而不是一个指针。

and processThread should be an std::thread, not a pointer to one.

有一个 runThreaded 方法作用于线程数据成员,你必须非常小心,在线程加入之前不要调用它多次。在构造函数中启动线程并将其加入析构函数可能更有意义。

Just a note on design: if you are to have a runThreaded method acting on a thread data member, you have to be very careful about not calling it more than once before the thread is joined. It might make more sense to launch the thread in the constructor and join it in the destructor.

这篇关于C ++ std :: thread的成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆