I am using an std::thread
in my C++
code to constantly poll for some data & add it to a buffer. I use a C++ lambda
to start the thread like this:
StartMyThread() {
thread_running = true;
the_thread = std::thread { [this] {
while(thread_running) {
GetData();
}
}};
}
thread_running
is an atomic<bool>
declared in class header. Here is my GetData
function:
GetData() {
//Some heavy logic which needs to be executed in a worker thread
}
Next I also have a StopMyThread
function where I set thread_running
to false so that it exits out of the while loop in the lambda block
.
StopMyThread() {
thread_running = false;
the_thread.join();
}
It works well. The thread starts & stops without crashing.
This C++ code is used on iOS, Android, OS X and Windows. My application UI has a button which requires me to start & stop the thread on a button press; this button can be frequently used in some occasions. I can see a split second delay in UI while stopping or starting the thread.
My question is: In C++, is this a correct way to start/stop a thread frequently ? I think that with this logic I am creating a new thread every-time. And as I understand, creating a new thread makes the OS allocate lot of new resources which can be time-consoming. And I think this is the mistake I am doing. How can I avoid this ?
How can make use of the same thread without allocating new one repeatedly throughout the application lifecycle, and just play/pause it when required ?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…