Ở đây chúng ta sẽ thấy, làm thế nào để kết thúc các luồng trong C ++ 11. C ++ 11 không có phương thức trực tiếp để kết thúc chuỗi.
Std ::future
Để tạo một đối tượng lời hứa, chúng ta phải làm theo cú pháp này -
std::promise<void> exitSignal;
Bây giờ tìm nạp đối tượng tương lai được liên kết từ đối tượng hứa đã tạo này trong hàm main -
std::future<void> futureObj = exitSignal.get_future();
Bây giờ, hãy chuyển hàm main trong khi tạo luồng, chuyển đối tượng tương lai -
std::thread th(&threadFunction, std::move(futureObj));
Ví dụ
#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;
} Đầu ra
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