Stop thread running QtConcurrent :: run?

Is it possible to stop a thread through its associated QFuture object? Currently, I have started the process of capturing videos like this.

this->cameraThreadRepresentation = QtConcurrent::run(this,&MainWindow::startLiveCapturing); 

Inside the startLiveCapturing-Method, an infinite loop is executed that captures images and displays them. Therefore, if the user wants to stop this process, he just has to click a button and this operation will stop. But it seems like I can't stop this thread by calling a cancel method like this?

 this->cameraThreadRepresentation.cancel(); 

What am I doing wrong and how can I stop this thread or operation.

+4
source share
3 answers

From the QtConcurrent :: run documentation:

Note that the QFuture returned by QtConcurrent :: run () does not support cancellation, suspension, or progress reporting. The returned QFuture can only be used to query the start / end status and return value of a function.

What could you do is press a button to set a logical flag in your main window and create an endless loop as follows:

 _aborted = false; forever // Qt syntax for "while( 1 )" { if( _aborted ) return; // do your actual work here } 
+5
source

Why don't you create a boolean flag that you can check inside the capture loop, and when it is set, it jumps out and the stream exits?

Sort of:

 MainWindow::onCancelClick() // a slot { QMutexLocker locker(&cancelMutex); stopCapturing = true; } 

And then for your streaming function:

 MainWindow::startLiveCapturing() { forever { ... QMutexLocker locker(&cancelMutex); if (stopCapturing) break; } } 
+2
source

In my capture loop, I use the flag to exit the loop and put it back in front of the last closing bracket, so I can properly disable the camera.

 void MyClass::CameraStream() { //open the camera etc.... bool run_capture_loop = true; while (run_capture_loop) { //capture and process image } //close camera etc.. return; } 
0
source

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


All Articles