C ++ std :: thread member function

I am trying to program a command line server that will receive information from the serial port, parse it and write to the internal object.

Then, upon request from the client, the server will return the requested information.

What I want to do is to place the receiver and parser parts in a separate thread so that the server works together without interfering with 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 destructor exampleClass::runThreaded(){ std::thread processThread(&exampleClass::completeProcess, this); } // Unfortunately The program ends up crashing here with CIGARET 
+6
source share
2 answers

You are using a local thread inside a member function. You must join it or separate it, and since it is local, you must do this in the function itself:

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

I assume that you really want to start the data stream and not start the local one. If you do this, you still have to join it somewhere, such as in a destructor. In this case, your method should be

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

and destructor

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

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

Just a design note: if you have a runThreaded method that acts on a data member of a stream, you must be very careful not to call it more than once before the stream is connected. It may make sense to start the stream in the constructor and join it in the destructor.

+8
source

The Thread object is on the stack and it will be destroyed at the end of the function. The destructor object of the std::terminate theme object if the thread is still running, as in your case. See here .

+3
source

Source: https://habr.com/ru/post/952292/


All Articles