更改向量时如何保持线程不打结?由 小码哥发布于

use*_*087 0 c++ multithreading vector thread-safety

该程序将崩溃,因为线程缠结......一个可能正在推动,而另一个正在尝试擦除。

我怎样才能做到这一点?

#include <thread>
#include <vector>

using namespace std;

vector<int> v_test;

void push()
{
    v_test.push_back(0);
}

void erase()
{
    if (v_test.size() > 0)
    {
        v_test.erase(v_test.begin());
    }
}

int main()
{
    thread w0(push);
    thread w1(erase);

    while (true) { Sleep(1000); }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 5

您需要同步线程,以便它们协调对向量的访问。例如,通过使用 a std::mutex,例如:

#include <thread>
#include <mutex>
#include <vector>
using namespace std;

vector<int> v_test;
mutex m_sync;

void push()
{
    lock_guard<mutex> lock(m_sync);
    v_test.push_back(0);
}

void erase()
{
    lock_guard<mutex> lock(m_sync);
    if (v_test.size() > 0)
    {
        v_test.erase(v_test.begin());
    }
}

int main()
{
    thread w0(push);
    thread w1(erase);

    while(true) {Sleep(1000);}
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 由于这看起来有点像生产者-消费者,因此 [`std::condition_variable`](https://en.cppreference.com/w/cpp/thread/condition_variable) 也可能会有所帮助。 (2认同)