여기에서 C++11에서 스레드를 종료하는 방법을 살펴보겠습니다. C++11에는 스레드를 종료하는 직접적인 방법이 없습니다.
std::future
하나의 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