std :: thread가 여전히 실행 중인지 확인하는 방법은 무엇입니까?
A가 있는지 어떻게 확인할 수 있습니다 std::thread
여전히 (플랫폼 독립적 인 방법으로)를 실행? 그것은 timed_join()
방법 이 부족하고 joinable()
그것을 의미하지 않습니다.
나는 std::lock_guard
스레드에서 뮤텍스를 잠그고 뮤텍스 의 try_lock()
방법을 사용하여 여전히 잠겨 있는지 (스레드가 실행 중인지) 결정하는 것을 생각했지만 불필요하게 복잡해 보입니다.
더 우아한 방법을 알고 있습니까?
업데이트 : 명확하게 : 스레드가 깨끗하게 종료되었는지 확인하고 싶습니다. 이 목적을 위해 '매달려있는'스레드가 실행중인 것으로 간주됩니다.
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;
/* Run some task on new thread. The launch policy std::launch::async
makes sure that the task is run asynchronously on a new thread. */
auto future = std::async(std::launch::async, [] {
std::this_thread::sleep_for(3s);
return 8;
});
// Use wait_for() with zero milliseconds to check thread status.
auto status = future.wait_for(0ms);
// Print status.
if (status == std::future_status::ready) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
auto result = future.get(); // Get result.
}
사용해야하는 경우 std::thread
다음 std::promise
개체를 가져 오는 데 사용할 수 있습니다 .
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
// Create a promise and get its future.
std::promise<bool> p;
auto future = p.get_future();
// Run some task on a new thread.
std::thread t([&p] {
std::this_thread::sleep_for(3s);
p.set_value(true); // Is done atomically.
});
// Get thread status using wait_for as before.
auto status = future.wait_for(0ms);
// Print status.
if (status == std::future_status::ready) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
t.join(); // Join thread.
}
이 두 예제는 모두 다음을 출력합니다.
Thread still running
물론 작업이 완료되기 전에 스레드 상태가 확인되기 때문입니다.
그러나 다른 사람들이 이미 언급 한 것처럼하는 것이 더 간단 할 수 있습니다.
#include <thread>
#include <atomic>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
std::atomic<bool> done(false); // Use an atomic flag.
/* Run some task on a new thread.
Make sure to set the done flag to true when finished. */
std::thread t([&done] {
std::this_thread::sleep_for(3s);
done = true;
});
// Print status.
if (done) {
std::cout << "Thread finished" << std::endl;
} else {
std::cout << "Thread still running" << std::endl;
}
t.join(); // Join thread.
}
편집하다:
다음 std::packaged_task
을 사용하는 std::thread
것보다 더 깨끗한 솔루션 을 위해 함께 사용할 수도 있습니다 std::promise
.
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
int main() {
using namespace std::chrono_literals;
// Create a packaged_task using some task and get its future.
std::packaged_task<void()> task([] {
std::this_thread::sleep_for(3s);
});
auto future = task.get_future();
// Run task on new thread.
std::thread t(std::move(task));
// Get thread status using wait_for as before.
auto status = future.wait_for(0ms);
// Print status.
if (status == std::future_status::ready) {
// ...
}
t.join(); // Join thread.
}
쉬운 해결책은 스레드가 정기적으로 true로 설정하고 상태를 알고 자하는 스레드가이를 확인하고 false로 설정하는 부울 변수를 갖는 것입니다. 오랫동안 변수가 거짓이면 스레드는 더 이상 활성 상태로 간주되지 않습니다.
A more thread-safe way is to have a counter that is increased by the child thread, and the main thread compares the counter to a stored value and if the same after too long time then the child thread is considered not active.
Note however, there is no way in C++11 to actually kill or remove a thread that has hanged.
Edit How to check if a thread has cleanly exited or not: Basically the same technique as described in the first paragraph; Have a boolean variable initialized to false. The last thing the child thread does is set it to true. The main thread can then check that variable, and if true do a join on the child thread without much (if any) blocking.
Edit2 If the thread exits due to an exception, then have two thread "main" functions: The first one have a try
-catch
inside which it calls the second "real" main thread function. This first main function sets the "have_exited" variable. Something like this:
bool thread_done = false;
void *thread_function(void *arg)
{
void *res = nullptr;
try
{
res = real_thread_function(arg);
}
catch (...)
{
}
thread_done = true;
return res;
}
This simple mechanism you can use for detecting finishing of a thread without blocking in join method.
std::thread thread([&thread]() {
sleep(3);
thread.detach();
});
while(thread.joinable())
sleep(1);
Create a mutex that the running thread and the calling thread both have access to. When the running thread starts it locks the mutex, and when it ends it unlocks the mutex. To check if the thread is still running, the calling thread calls mutex.try_lock(). The return value of that is the status of the thread. (Just make sure to unlock the mutex if the try_lock worked)
One small problem with this, mutex.try_lock() will return false between the time the thread is created, and when it locks the mutex, but this can be avoided using a slightly more complex method.
Surely have a mutex-wrapped variable initialised to false
, that the thread sets to true
as the last thing it does before exiting. Is that atomic enough for your needs?
You can always check if the thread's id is different than std::thread::id() default constructed. A Running thread has always a genuine associated id. Try to avoid too much fancy stuff :)
참고URL : https://stackoverflow.com/questions/9094422/how-to-check-if-a-stdthread-is-still-running
'IT박스' 카테고리의 다른 글
ISNULL을 사용하는 것과 COALESCE를 사용하여 특정 조건을 확인합니까? (0) | 2020.10.30 |
---|---|
다른 CSS 클래스 내의 CSS 클래스를 대상으로 지정 (0) | 2020.10.30 |
조각보기가 사용자에게 표시되는지 테스트하는 방법은 무엇입니까? (0) | 2020.10.30 |
Windows 10에서 "서버 DNS 주소를 찾을 수 없음"오류를 해결하려면 어떻게합니까? (0) | 2020.10.30 |
ILMerge 모범 사례 (0) | 2020.10.30 |