상식닷컴
로그인
가입하기
2026년 상식닷컴 선정 식당 & 카페 리스트
2025년 2026년 신상 호텔 리스트
최근에 오픈한 호텔을 찾는다면 살펴보세요
일주일 식단표 어플
자동 일주일 식단표 어플
안드로이드
아이폰
주식 & 코인 차트의 신
1000만원으로 2000만원 만들기 프로젝트
수정하기 - C++에서 condition_variable의 사용법은?
닉네임
비밀번호
제목
내용
[이미지 업로드는 권한이 있는 사람만 가능. 하단 카톡으로 연락]
C++에서 `condition_variable`은 스레드 간의 동기화를 위한 중요한 도구입니다. 이 객체는 특정 조건이 충족될 때까지 스레드를 대기시키고, 조건이 충족되면 대기 중인 스레드를 깨우는 기능을 제공합니다. `condition_variable`은 주로 생산자-소비자 문제와 같은 상황에서 사용됩니다. 기본 개념 `condition_variable`은 두 가지 <a href='https://sangseek.com/sangseeks/주요 작업/ko'>주요 작업</a>을 지원합니다: 1. 대기 : 스레드가 특정 조건이 충족될 때까지 대기하도록 합니다. 2. 신호 : 조건이 충족되었음을 다른 스레드에 알립니다. 이러한 기능은 `std::mutex`와 함께 사용되어야 하며, `std::<a href='https://sangseek.com/sangseeks/unique_lock/ko'>unique_lock</a>`을 통해 mutex를 관리합니다. 사용법 1. 헤더 파일 포함 : `condition_variable`을 사용하기 위해서는 `<condition_variable>` 헤더 파일을 포함해야 합니다. ```cpp include <condition_variable> include <mutex> include <thread> include <iostream> ``` 2. 변수 선언 : `condition_variable`, `mutex`, <a href='https://sangseek.com/sangseeks/그리고/ko'>그리고</a> 조건을 나타내는 변수를 선언합니다. ```cpp std::condition_variable cv; std::mutex mtx; bool ready = false; // 조건 변수 ``` 3. 대기하는 스레드 : 조건이 충족될 때까지 대기하는 스레드를 구현합니다. `std::unique_lock`을 사용하여 mutex를 잠그고, `wait` 메서드를 호출하여 대기합니다. ```cpp void waitForWork() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [] { return ready; }); // ready가 true가 될 때까지 대기 std::cout << "Work is done!" << std::endl; } ``` 4. 신호를 보내는 스레드 : 조건이 충족되었을 때 `<a href='https://sangseek.com/sangseeks/notify_one/ko'>notify_one</a>` 또는 `<a href='https://sangseek.com/sangseeks/notify_all/ko'>notify_all</a>` 메서드를 호출하여 대기 중인 스레드를 깨웁니다. ```cpp void doWork() { { std::<a href='https://sangseek.com/sangseeks/lock_guard/ko'>lock_guard</a><std::mutex> lock(mtx); ready = true; // 조건을 충족 } cv.notify_one(); // 대기 중인 스레드 중 하나를 깨움 } ``` 5. 스레드 실행 : 메인 함수에서 스레드를 생성하고 실행합니다. ```cpp int main() { std::thread worker(waitForWork); std::thread producer(doWork); worker.join(); producer.join(); return 0; } ``` 전체 코드 예제 아래는 `condition_variable`을 사용하는 전체 예제입니다. ```cpp include <condition_variable> include <mutex> include <thread> include <iostream> std::condition_variable cv; std::mutex mtx; bool ready = false; void waitForWork() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, [] { return ready; }); // ready가 true가 될 때까지 대기 std::cout << "Work is done!" << std::endl; } void doWork() { { std::lock_guard<std::mutex> lock(mtx); ready = true; // 조건을 충족 } cv.notify_one(); // 대기 중인 스레드 중 하나를 깨움 } int main() { std::thread worker(waitForWork); std::thread producer(doWork); worker.join(); producer.join(); return 0; } ``` 주의사항 - <a href='https://sangseek.com/sangseeks/Mutex/ko'>Mutex</a>와 함께 사용 : `condition_variable`은 반드시 `mutex`와 함께 사용해야 합니다. 대기 중인 스레드는 mutex를 잠그고 있어야 하며, 조건이 충족되면 mutex를 해제하고 대기 상태에서 벗어납니다. - 스레드 안전성 : `condition_variable`과 관련된 모든 데이터는 스레드 안전하게 접근해야 합니다. 이를 위해 mutex를 사용하여 데이터 접근을 보호해야 합니다. - notify_all vs notify_one : `notify_one`은 대기 중인 스레드 중 하나만 깨우고, `notify_all`은 모든 대기 중인 스레드를 깨웁니다. 상황에 따라 적절한 방법을 선택해야 합니다. 결론 `condition_variable`은 C++에서 스레드 간의 동기화를 효과적으로 관리하는 데 매우 유용한 도구입니다. 이를 통해 복잡한 스레드 간의 상호작용을 간단하게 처리할 수 있으며, 생산자-소비자 문제와 같은 다양한 동기화 문제를 해결할 수 있습니다.
이용안내
커뮤니티 이용안내
×
- 게시한 게시글로 발생하는 문제는 게시자에게 책임이 있습니다.
- 게시글이 타인/타업체의 저작권을 침해할 경우 모든 책임은 게시자에게 있습니다. 게시자가 모든 손해를 부담해야 합니다.
- 상식닷컴 운영자는 게시자와 상의하지 않고 게시글을 수정 또는 삭제할 수 있습니다.
- 상식닷컴 운영자는 깨끗한 커뮤니티 공간을 만드는 것이 1순위입니다.
수정하기
취소하기