cpp_Thread_CV - 8BitsCoding/RobotMentor GitHub Wiki
- ์ด๋ฒคํธ ๊ฐ์ฒด
- ์ ํธ๋ฅผ ๋ฐ์ ๋๊น์ง ํ์ฌ ์ฐ๋ ๋์ ์คํ์ ๋ฉ์ถ๋ค.
- notify_one(), notify_all()
- ๋ฉ์ถฐ ๋์ ์ฐ๋ ๋ ํ๋ ๋๋ ์ ๋ถ๋ฅผ ๋ค์ ์คํ์ํด
- wait(), wait_for(), wait_until()
- ์กฐ๊ฑด ๋ณ์์ ์กฐ๊ฑด์ ์ถฉ์กฑ์ํฌ๋๊น์ง ๋๋ ์ผ์ ์๊ฐ ๋์ ํ์ฌ์ฐ๋ ๋์ ์คํ์ ๋ฉ์ถค
-
std::unique_lock
์ ์ฌ์ฉํด์ผ ํจ
- ๊ธฐ๋ณธ์ ์ผ๋ก scoped lock
- ์์ฑ์์ lock์ ์ ๊ทธ์ง ์์ ์๋ ์์(๋ ๋ฒ์งธ ๋งค๊ฐ๋ณ์๋ก std::defer_lock์ ์ ๋ฌํ ๊ฒ)
- std::recursive_mutex์ ํจ๊ป ์จ์ ์ฌ๊ท์ ์ผ๋ก ์ ๊ธ ์ ์์
- ์กฐ๊ฑด ๋ณ์์ ์ธ ์ ์๋ ์ ์ผํ lock
#include <iostream>
#include <mutex>
#include <queue>
static std::mutex sQueueLock;
static std::condigion_variable sEvent;
static std::queue<int> sQueue;
void Consume()
{
while(true)
{
int val;
{
std::unique_lock<std::mutex> lock(sQueueLock);
sEvent.wait(lock);
val = sQueue.front();
sQueue.pop();
}
std::cout << val << std::endl;
}
}
void Produce()
{
std::unique_lock<std::mutex> lock(sQueueLock);
sQueue.push(1);
sEvent.notify_one();
}
int main()
{
std::thread producer(Produce);
std::thread consumer(Consume);
producer.join();
consumer.join();
return 0;
}
-
wait()
ํจ์๋ ํ์ฌ ์ฐ๋ ๋ ๋ฎคํ ์ค์ ์ ๊ธ์ ํ๊ณnotify_one()
,notify_all()
์ ๊ธฐ๋ค๋ฆฐ๋ค. - ๊นจ์ด๋๋ฉด ๋ค์ ๋ฎคํ ์ค๋ฅผ ์ ๊ทผ๋ค.
์ ์ฝ๋์ ๋ฌธ์ ์ ์
notift_xxx()
๊ฐwait()
๋ณด๋ค ๋จผ์ ํธ์ถ๋๋ฉด ํด๋น ์ฐ๋ ๋๋ ์์ํ ๊ธฐ๋ค๋ฆฌ๋๋ฐ ์๋ค.
#include <iostream>
#include <mutex>
#include <queue>
static std::mutex sQueueLock;
static std::condigion_variable sEvent;
static std::queue<int> sQueue;
void Consume()
{
while(true)
{
int val;
{
std::unique_lock<std::mutex> lock(sQueueLock);
sEvent.wait(lock, []{return !sQueue.empty();});
// wait๋ฅผ ๊ฑธ๋ ์กฐ๊ฑด์ ๊ฑธ์ด๋๋ค.
val = sQueue.front();
sQueue.pop();
}
std::cout << val << std::endl;
}
}
void Produce()
{
std::unique_lock<std::mutex> lock(sQueueLock);
sQueue.push(1);
sEvent.notify_one();
}
int main()
{
std::thread producer(Produce);
std::thread consumer(Consume);
producer.join();
consumer.join();
return 0;
}