Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++11에서 스레드를 어떻게 종료합니까?

<시간/>

여기에서 C++11에서 스레드를 종료하는 방법을 살펴보겠습니다. C++11에는 스레드를 종료하는 직접적인 방법이 없습니다.

std::future는 쓰레드에 사용될 수 있으며, 미래의 값을 사용할 수 있을 때 종료되어야 합니다. 쓰레드에 시그널을 보내고 싶지만 실제 값을 보내지 않는다면 void 타입 객체를 전달할 수 있다.

하나의 promise 객체를 생성하려면 다음 구문을 따라야 합니다 -

std::promise<void> exitSignal;

이제 main 함수에서 생성된 promise 개체에서 연결된 future 개체를 가져옵니다.

std::future<void> futureObj = exitSignal.get_future();

이제 스레드를 생성하는 동안 main 함수를 전달하고 future 객체를 전달합니다 -

std::thread th(&threadFunction, std::move(futureObj));

예시

#include <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include <future>
using namespace std;
void threadFunction(std::future<void> future){
   std::cout << "Starting the thread" << std::endl;
   while (future.wait_for(std::chrono::milliseconds(1)) == std::future_status::timeout){
      std::cout << "Executing the thread....." << std::endl;
      std::this_thread::sleep_for(std::chrono::milliseconds(500)); //wait for 500 milliseconds
   }
   std::cout << "Thread Terminated" << std::endl;
}
main(){
   std::promise<void> signal_exit; //create promise object
   std::future<void> future = signal_exit.get_future();//create future objects
   std::thread my_thread(&threadFunction, std::move(future)); //start thread, and move future
   std::this_thread::sleep_for(std::chrono::seconds(7)); //wait for 7 seconds
   std::cout << "Threads will be stopped soon...." << std::endl;
   signal_exit.set_value(); //set value into promise
   my_thread.join(); //join the thread with the main thread
   std::cout << "Doing task in main function" << std::endl;
}

출력

Starting the thread
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Executing the thread.....
Threads will be stopped soon....
Thread Terminated
Doing task in main function