๐๐ป ์๋๋ ์ค๋ ๋์์ 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