반응형
"이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다."
👨💻 안녕하세요, 윌리 프로젝트의 윌리 입니다.
C++ 에서 thread 의 joinable() 은 무엇이며, 어떻게 활용할 수 있는지 간략히 알아보았습니다.
질문 >
C++ 에서 thread 의 joinable() 은 무엇이며, 어떻게 활용할 수 있나요?
답변 >
std::thread::joinable()란?
C++의 std::thread::joinable() 함수는 스레드 객체가 실행 가능한 상태인지 확인하는 데 사용됩니다.
- joinable()는 스레드가 유효한 상태인지를 나타내는 불리언 값을 반환하며,
- 스레드가 실행 중이거나 종료 대기 중일 경우 true를 반환합니다.
- 그렇지 않은 경우 false를 반환합니다.
특징
- 스레드 유효성 확인:
- 스레드 객체가 실행 가능하거나, 아직 join()이나 detach()를 호출하지 않은 경우 true를 반환합니다.
- join() 호출 전 필수 확인:
- join()을 호출하려면 스레드가 반드시 joinable() 상태여야 합니다.
- 그렇지 않으면 std::system_error 예외가 발생합니다.
- 빈 스레드 객체:
- 스레드가 기본 생성된 상태(예: std::thread t;)이거나, join() 또는 detach()가 호출된 후에는 joinable()이 false를 반환합니다.
기본 사용법
1. 단일 스레드에서의 joinable() 사용
#include <iostream>
#include <thread>
void worker() {
std::cout << "Worker thread is running." << std::endl;
}
int main() {
std::thread t(worker);
if (t.joinable()) {
std::cout << "Thread is joinable. Joining now." << std::endl;
t.join();
} else {
std::cout << "Thread is not joinable." << std::endl;
}
return 0;
}
출력 예시:
Worker thread is running.
Thread is joinable. Joining now.
2. 기본 생성된 스레드 확인
#include <iostream>
#include <thread>
int main() {
std::thread t; // 기본 생성된 빈 스레드
if (t.joinable()) {
std::cout << "Thread is joinable." << std::endl;
} else {
std::cout << "Thread is not joinable." << std::endl;
}
return 0;
}
출력 예시:
Thread is not joinable.
3. join() 호출 후 joinable() 상태
#include <iostream>
#include <thread>
void worker() {
std::cout << "Worker thread is running." << std::endl;
}
int main() {
std::thread t(worker);
t.join(); // 스레드 종료 대기
if (t.joinable()) {
std::cout << "Thread is joinable." << std::endl;
} else {
std::cout << "Thread is not joinable after join." << std::endl;
}
return 0;
}
출력 예시:
Worker thread is running.
Thread is not joinable after join.
활용 예제
4. 멀티스레드 관리
여러 스레드를 관리하면서 joinable()을 사용해 안전하게 join()을 호출합니다.
#include <iostream>
#include <thread>
#include <vector>
void worker(int id) {
std::cout << "Thread " << id << " is working." << std::endl;
}
int main() {
const int numThreads = 3;
std::vector<std::thread> threads;
// 여러 스레드 생성
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(worker, i);
}
// 모든 스레드 join
for (auto& t : threads) {
if (t.joinable()) {
t.join();
}
}
return 0;
}
5. 예외 상황에서 안전한 종료
#include <iostream>
#include <thread>
#include <stdexcept>
void worker() {
std::cout << "Worker thread is running." << std::endl;
throw std::runtime_error("An error occurred in the thread.");
}
int main() {
std::thread t;
try {
t = std::thread(worker);
t.join();
} catch (const std::exception& e) {
std::cerr << "Exception: " << e.what() << std::endl;
if (t.joinable()) {
t.join(); // 스레드 종료 대기
}
}
return 0;
}
출력 예시:
Worker thread is running.
Exception: An error occurred in the thread.
joinable()가 false를 반환하는 경우
- 빈 스레드 객체:
- 스레드가 생성되지 않은 상태(예: 기본 생성자 호출).
- join() 호출 후:
- 스레드가 종료되고 join()이 호출된 후에는 더 이상 joinable()이 아닙니다.
- detach() 호출 후:
- 스레드가 분리된 후에는 더 이상 관리되지 않으므로 joinable()이 false를 반환합니다.
- 복사 금지:
- std::thread 객체는 복사할 수 없으므로, 잘못된 복사 시도 후에는 joinable()이 false일 수 있습니다.
주의사항
- joinable()를 사용하지 않고 join() 호출:
- joinable() 상태가 아닌 스레드에 대해 join()을 호출하면 std::system_error 예외가 발생합니다.
- joinable()와 스레드 수명:
- joinable()는 스레드의 수명을 안전하게 관리하기 위해 사용됩니다.
- 항상 join()이나 detach()를 호출하여 스레드 자원을 정리해야 합니다.
결론
std::thread::joinable()는 스레드의 상태를 확인하고 안전하게 관리하기 위한 중요한 도구입니다. 이를 활용하면 스레드가 실행 가능 상태인지 확인하고, join() 호출 시의 예외 상황을 방지할 수 있습니다.
- 주요 활용:
- join() 호출 전 스레드 상태 확인.
- 멀티스레드 관리 시 안전한 종료 구현.
- 예외 처리 시 스레드 자원 누수를 방지.
joinable()를 적절히 사용하면 멀티스레드 프로그램의 안정성과 유지보수성을 크게 향상시킬 수 있습니다.
🎬 유튜브 채널 🎬
위로그@WiLog
📢 안녕하세요, 위로그@WiLog 시청자 여러분, 저는 윌리(Willee) 입니다. 📢 위로그@WiLog 는 자기계발을 목적으로 하는 채널 입니다. 📢 오늘도 즐겁게~ 자신을 위한 계발을 함께 해보아요~ d^_^b 📌
www.youtube.com
🎬 치지직 채널 🎬
위로그 채널 - CHZZK
지금, 스트리밍이 시작됩니다. 치지직-
chzzk.naver.com
반응형
'프로그래밍' 카테고리의 다른 글
👨💻 [C++] C++ 에서 std::atomic_ 로 시작하는 데이터 타입들은 무엇이며, 어떻게 활용할 수 있나요? (0) | 2025.01.23 |
---|---|
👨💻 [C++] C++ 에서 std::condition_variable 은 무엇이며, 어떻게 활용할 수 있나요? (0) | 2025.01.23 |
👨💻 [C++] C++ 에서 thread 의 join() 은 무엇이며, 어떻게 활용할 수 있나요? (0) | 2025.01.23 |
👨💻 [C++] C++ 에서 std::this_thread::get_id() 는 무엇이고, 어떻게 활용할 수 있나요? (0) | 2025.01.23 |
👨💻 [Go] Go 에서 Singleton 디자인 패턴은 어떻게 설계할 수 있나요? (0) | 2025.01.22 |