cpp_Thread_CV - 8BitsCoding/RobotMentor GitHub Wiki

cpp_Thread_CV

  • ์ด๋ฒคํŠธ ๊ฐœ์ฒด
  • ์‹ ํ˜ธ๋ฅผ ๋ฐ›์„ ๋•Œ๊นŒ์ง€ ํ˜„์žฌ ์“ฐ๋ ˆ๋“œ์˜ ์‹คํ–‰์„ ๋ฉˆ์ถ˜๋‹ค.
  • 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()๋ณด๋‹ค ๋จผ์ € ํ˜ธ์ถœ๋˜๋ฉด ํ•ด๋‹น ์“ฐ๋ ˆ๋“œ๋Š” ์˜์›ํžˆ ๊ธฐ๋‹ค๋ฆฌ๋Š”๋ฐ ์žˆ๋‹ค.


์˜ฌ๋ฐ”๋ฅธ 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;
}
โš ๏ธ **GitHub.com Fallback** โš ๏ธ