यदि आप C ++ 11 का उपयोग करने std::asyncऔर std::futureअपने कार्यों को चलाने के लिए तैयार हैं, तो आप यह जांचने wait_forके std::futureलिए फ़ंक्शन का उपयोग कर सकते हैं कि क्या थ्रेड अभी भी इस तरह से चल रहा है:
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
auto future = std::async(std::launch::async, [] {
std::this_thread::sleep_for(3s);
return 8;
});
auto status = future.wait_for(0ms);
if (status == std::future_status::ready) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
auto result = future.get();
}
यदि आपको उपयोग करना चाहिए std::threadतो आप std::promiseभविष्य की वस्तु प्राप्त करने के लिए उपयोग कर सकते हैं :
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
std::promise<bool> p;
auto future = p.get_future();
std::thread t([&p] {
std::this_thread::sleep_for(3s);
p.set_value(true);
});
auto status = future.wait_for(0ms);
if (status == std::future_status::ready) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
t.join();
}
ये दोनों उदाहरण आउटपुट देंगे:
Thread still running
यह निश्चित रूप से है क्योंकि कार्य समाप्त होने से पहले थ्रेड स्थिति की जाँच की जाती है।
लेकिन फिर से, यह सरल हो सकता है जैसे कि दूसरों ने पहले ही उल्लेख किया है:
#include <thread>
#include <atomic>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
std::atomic<bool> done(false);
std::thread t([&done] {
std::this_thread::sleep_for(3s);
done = true;
});
if (done) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
t.join();
}
संपादित करें:
std::packaged_taskउपयोग करने की std::threadतुलना में क्लीनर समाधान के लिए उपयोग के लिए भी है std::promise:
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
std::packaged_task<void()> task([] {
std::this_thread::sleep_for(3s);
});
auto future = task.get_future();
std::thread t(std::move(task));
auto status = future.wait_for(0ms);
if (status == std::future_status::ready) {
}
t.join();
}
wait()इसके लिए उम्मीद करते हैं और यदि ऐसा है, तो यदि आपने इसकेwait()लिए अभी तक एड नहीं किया है, तो वह परिभाषा के अनुसार चलना चाहिए। लेकिन यह तर्क अक्षम हो सकता है।