gpt4 book ai didi

c++ - 通过多个线程访问 vector ?

转载 作者:行者123 更新时间:2023-11-28 07:49:09 26 4
gpt4 key购买 nike

如何防止 vector 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);
}
}

最佳答案

要从多个线程访问一个 vector ,您需要添加 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;
}

关于c++ - 通过多个线程访问 vector ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14211696/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com