2013-01-08 3 views
0

어떻게하면 벡터 v가 충돌하지 않도록 보호 할 수 있습니까? 그리고 또 다른 질문은, 왜 그것은 이미 추락하지 않았습니까, 안 그래야합니까?여러 스레드에서 벡터에 액세스 하시겠습니까?

#include <Windows.h> 
#include <thread> 
#include <vector> 
#include <algorithm> 
#include <iostream> 

using namespace std; 

vector<int> v; 

void a() 
{ 
    while (true) 
    { 
     v.push_back(1); 
     Sleep(100); 
    } 
} 

void b() 
{ 
    while (true) 
    { 
     if (!v.empty()) 
     { 
      v.erase(v.begin()); 
     } 
     Sleep(100); 
    } 
} 

void c() 
{ 
    while (true) 
    { 
     v.push_back(1); 

     Sleep(100); 
    } 
} 

int main() 
{ 
    thread(&a).detach(); 
    thread(&b).detach(); 
    thread(&c).detach(); 

    while (true) 
    { 

     for (int i = 0; i < v.size(); i++) 
     { 
      v[i]++; 
     } 


     cout << v.size() << endl; 


     if (!v.empty()) 
      v.erase(v.begin()); 

     Sleep(100); 
    } 
} 
+4

[mutex] (http://en.cppreference.com/w/cpp/thread/mutex)? –

+0

가능한 복제본 : http://stackoverflow.com/questions/12260946/c-access-to-vector-from-multiple-threads – Default

+0

다른 사람들이 말한 것을 추가하기 만하면 여러 스레드에서 벡터 내용을 읽는 경우 , 스레드로부터 안전합니다. – NeonGlow

답변

1

여러 스레드에서 하나의 벡터에 액세스하려면, 당신은 표준 : 뮤텍스를 추가 할 필요가 은 관용적 인 방법은 RAII를 구현하는 데모 코드는 아래를 참조하는 것입니다

#include <mutex> 
#include <thread> 

class raii_vector 
{ 
public: 
    raii_vector() { } 
    void Add() 
    { 
    std::lock_guard<std::mutex> lock(m_); 
    v_.push_back(1); 
    } 

    void Remove() 
    { 
    std::lock_guard<std::mutex> lock(m_); 
    if (!v_.empty()) 
    { 
     v_.erase(v_.begin()); 
    } 
    } 

private: 
    std::mutex  m_; 
    std::vector<int> v_; 
}; 

raii_vector rv; 

void a() 
{ 
    while (true) 
    { 
    rv.Add(); 
    std::cout << "adding " << std::endl; 
    std::chrono::milliseconds dura(100); 
    std::this_thread::sleep_for(dura); 
    } 
} 

void b() 
{ 
    while (true) 
    { 
    std::cout << "removing " << std::endl; 
    rv.Remove(); 
    std::chrono::milliseconds dura(100); 
    std::this_thread::sleep_for(dura); 
    } 
} 

int main(int argc, char* argv[]) 
{ 
    std::thread t1(a); 
    std::thread t2(b); 

    t1.join(); 
    t2.join(); 

    return 0; 
} 
+0

이것이 내가 찾고 있던 것입니다. – Dean

관련 문제