2013-04-29 3 views
1

내 프로그램에 세 개의 스레드가 있으며 동기화 및 스레드 안전성을 배우려고합니다. 아래에서는 다른 스레드가 수행하는 작업에 대해 간략하게 설명합니다. 대신 이벤트를 사용하여 무한대로 읽는 대신 다른 스레드에서 각 프로세스를 트리거하는 방법을 배우고 싶습니다.이 스레드는 동시성 문제를 발생시킵니다.다중 스레드 및 이벤트 사용

인터넷 검색은 많은 옵션을 던지지 만,이 경우 구현하는 것이 가장 좋은지 잘 모르겠습니다. 가장 좋은 방법을 배우는 표준 방법/이벤트에 대한 방향을 제시 할 수 있습니까?

저는 VS 2012에서 이것을하고 있으며, 이상적으로는 외부 라이브러리를 사용하지 않을 것입니다. 후원.

스레드 1 : 메시지를 받고 글로벌 큐인 queue<my_class> msg_in으로 푸시합니다.

스레드 2 : 무한 루프 (예 : while(1)); if (!msg_in.empty())까지 기다린 후 일부 처리를 수행하고이를 글로벌 map<map<queue<my_class>>> msg_out으로 푸시합니다.

while (1) 
{ 
    if (!msg_in.empty()) 
    { 
     //processes 
     msg_map[i][j].push(); //i and j are int (irrelevant here) 
    } 

} 

스레드 3 :

while (1) 
{ 
    if (msg_map.find(i) != msg_map.end()) 
    { 
     if (!msg_map[i].find(j)->second.empty()) 
     { 
      //processes 
     } 
    } 
} 

답변

0

귀하의 문제는 생산자 소비자 문제입니다. 이벤트에 조건 변수를 사용할 수 있습니다. 여기에 그 중 하나의 예가 있습니다 : http://en.cppreference.com/w/cpp/thread/condition_variable

나는 그것을 당신의 필요에 맞게 수정했습니다.

#include "MainThread.h" 


#include <iostream> 
#include <string> 
#include <thread> 
#include <mutex> 
#include <atomic> 
#include <condition_variable> 

std::mutex m; 
std::condition_variable cv; 
bool ready = false; 
bool processed = false; 

void worker_thread(unsigned int threadNum) 
{ 
    // Wait until main() sends data 
    { 
     std::unique_lock<std::mutex> lk(m); 
     cv.wait(lk, []{return ready;}); 
    } 

    std::cout << "Worker thread "<<threadNum <<" is processing data"<<std::endl; 

    // Send data back to main() 
    { 
     std::lock_guard<std::mutex> lk(m); 
     processed = true; 
     std::cout << "Worker thread "<< threadNum <<" signals data processing completed\n"; 
    } 
    cv.notify_one(); 
} 


int initializeData() 
{ 
    // send data to the worker thread 
    { 
     std::lock_guard<std::mutex> lk(m); 
     ready = true; 
     std::cout << "Data initialized"<<std::endl; 
    } 
    cv.notify_one(); 
    return 0; 
} 

int consumerThread(unsigned int nbThreads) 
{ 
    std::atomic<unsigned int> nbConsumedthreads=0; 
    while (nbConsumedthreads<nbThreads) 
    { 
     std::unique_lock<std::mutex> lk(m); 
     cv.wait(lk, []{return processed;}); 
     std::cout<<"Data processed counter="<<nbConsumedthreads << " "<< std::endl; 
     ++nbConsumedthreads; 
     cv.notify_one(); 
    } 

    return 0; 
} 

int main() 
{ 
    const unsigned int nbThreads=3; 
    std::thread worker1(worker_thread,1); 
    std::thread worker2(worker_thread,2); 
    std::thread worker3(worker_thread,3); 

    std::thread init(initializeData); 

    std::thread consume(consumerThread, nbThreads); 



    worker1.join(); 
    worker2.join(); 
    worker3.join(); 

    init.join(); 

    consume.join(); 

    return 0; 
} 

희망 사항은 더 많은 정보가 필요하면 알려주세요.