GameChoi 2023. 1. 3. 18:26

1. Producer & Consumer

1.1 Producer & Consumer

 - 멀티 쓰레드 프로그램에서 가장 많이 등장하는 패턴

   - 생산자는 무언가 처리할 일을 받아오는 쓰레드를 의미

   - 소비자는 받은 일을 처리하는 쓰레드를 의미
 - Queue 사용

   - FIFO

     - 먼저 처리할 일을 받으면 먼저 처리함

1.2 Program

1.2.1 Main

 - Queue, Mutex Create

   - 일감을 저장할 수 있게 큐 생성 및 상호배제를 하기 위해 Mutex 생성

int main()
{
    vector<std::thread> workers;
    queue<int> q;
    std::mutex m;
   
    workers.push_back(std::thread(producer, std::ref(q), std::ref(m)));
    workers.push_back(std::thread(consumer, std::ref(q), std::ref(m)));
    
    for (int i = 0; i < 2; i++) workers[i].join();
}

1.2.2 Producer

 - 10ms 마다 일감을 만듦

void producer(queue<int>& q, std::mutex& m)
{
    for (int i = 0; i < 100; i++)
    {
        std::this_thread::sleep_for(10ms);
        unique_lock<mutex> lock(m);
        q.push(i * 10);
    }
}

1.2.3 Consumer

 - 일감이 있는지 확인을 해 없다면 10ms를 기다리고 다시 실행

 - 만약 일감이 있으면 값을 받아서 출력

void consumer(queue<int>& q, std::mutex& m)
{
    while(true)
    {
        unique_lock<mutex> lock(m);
        if (q.empty() == false)
        {
            int data = q.front();
            q.pop();
            cout << data << endl;
        }

        std::this_thread::sleep_for(10ms);
        continue;
    }
}

1.2.4 Print

Print