【问题标题】:Accessing vector over multiple threads?通过多个线程访问向量?
【发布时间】:2013-01-08 09:20:21
【问题描述】:

如何保护向量 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);
    }
}

【问题讨论】:

标签: c++ multithreading mutex


【解决方案1】:

要从多线程访问一个向量,需要添加std::mutex,惯用的方法是实现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;
}

【讨论】:

    【解决方案2】:

    当想要使用来自多线程的向量等数据结构时,我发现Intel Threading Building Blocks library 非常有用。

    【讨论】:

      猜你喜欢
      • 2012-08-28
      • 2011-12-06
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多