👉🏻 아래는 스레드에서 detach와 join 에 대한 설명입니다.
Below is an explanation of detach and join in threads.
✔️ detach
— detach방식은 스레드 동작을 백그라운드에서 완전히 분리시킵니다.
The detach method completely separates thread operations from the background.
— 완전히 분리되어 독립적으로 동작하기 때문에 종료시점을 알기 어렵고 제어가 어렵습니다.
Because they are completely separated and operate independently, it is difficult to know the termination point and difficult to control.
— 비교적 간단한 작업에 사용합니다.
It is used for relatively simple tasks.
✔️ join
— join()은 joinable()이 true이면 스레드를 대기상태로 만드는 함수입니다.
join() is a function that puts a thread into a waiting state if joinable() is true.
— join을 사용하는 방식은 스레드의 종료지점을 관리 가능하기때문에 복잡한 서버나 대규모 프로그램에서 사용됩니다.
The join method is used in complex servers or large-scale programs because it allows for the management of thread termination points.
✔️ 코드 / Code
— detach.cpp
#include <iostream>
#include <thread>
void worker(int id) {
std::cout << "Worker " << id << " started.\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Worker " << id << " finished.\n";
}
int main() {
for(int i = 0; i < 3; ++i) {
std::thread t(worker, i);
// 스레드를 분리하여 독립 실행
// Separate threads for independent execution
t.detach();
}
std::cout << "Main thread finished without waiting.\n";
// 메인 스레드가 여기서 종료되어도 worker 스레드는 백그라운드에서 계속 동작할 수 있음
// Even if the main thread terminates here, the worker thread can continue to run in the background
// 스레드가 작업 할 시간 확보용(디버깅 목적)
// To secure time for the thread to work (for debugging purposes)
std::this_thread::sleep_for(std::chrono::seconds(2));
return 0;
}
— vt.cpp
#include <iostream>
#include <thread>
#include <vector>
void worker(int id) {
std::cout << "Worker " << id << " started.\n";
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Worker " << id << " finished.\n";
}
int main() {
std::vector<std::thread> threads;
for(int i = 0; i < 3; ++i) {
std::thread t(worker, i);
// 스레드 객체를 벡터에 저장
// Store thread objects in a vector
threads.push_back(std::move(t));
}
// 모든 스레드가 종료될 때까지 기다림
// Wait until all threads terminate
for(auto &t : threads) {
if(t.joinable()) {
t.join();
}
}
// 벡터에서 스레드 객체 제거
// Remove thread objects from vector
threads.clear();
std::cout << "All workers completed.\n";
return 0;
}
✔️ 컴파일 / Compiling
g++ vt.cpp -o vt -std=c++17 -pthread
g++ detach.cpp -o detach -std=c++17 -pthread
✔️실행 / Run
./vt
./detach