2013-01-08 63 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

A [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

访问从多个线程一个载体,你需要添加的std ::互斥体,惯用的方式是实现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