通过多个线程访问vector
Accessing vector over multiple threads?
如何保护矢量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);
}
}
要从多个线程访问一个向量,需要添加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;
}
当想要使用数据结构时,例如来自多个线程的向量,我发现英特尔线程构建块库非常有用。
相关文章:
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 使用 std::vector<double> 访问由 std::unique_ptr<double[2] 管理的数据>
- 如何访问vector<pair<int, pair<int, int>>> D[20]?
- 访问 vector 中的子结构体值
- 通过 vector.begin() 命令访问 vector 的第一个元素
- 如何在 Boost Python 中访问 Vector
- 使用move_iterator访问vector
- 访问vector的vector中的c++ vector而不复制它
- 如何使用常量引用访问 vector<int*> 的元素?
- 在c++中访问vector中的数组
- 当访问Vector中的实例时,shared_ptr的Vector给出seg错误
- 访问vector元素属性的最佳方法
- 访问vector的内容
- 在pop_back()之后无法访问vector(分段错误)
- 访问Vector的元素- c++
- 使用std::vector::at或std::vector::operator[]访问vector:中存储的对象
- 如何在c++中从指向vector的指针访问vector的内容
- 使用迭代器访问 vector<std::unique_ptr > 的元素<T>?
- 在类函数中访问vector的元素
- 通过多个线程访问vector