【发布时间】:2019-11-04 00:20:25
【问题描述】:
我对特定的多线程情况感到困惑,无法找到对这种情况的明确解释。在下面的代码中,两个自定义线程是写+读线程安全的,但主线程也在同时读取。所以这是我的问题:我是否也必须对读取功能进行互斥?还是绝对不可能使应用程序崩溃,例如向量中先前删除的指针的原因?希望大家能帮帮我,谢谢!
#include <thread>
#include <mutex>
#include <iostream>
#include <vector>
int g_i = 0;
std::vector<int> test;
std::mutex g_i_mutex; // protects g_i
void safe_increment()
{
std::lock_guard<std::mutex> lock(g_i_mutex);
++g_i;
test.resize(test.size() + 1, 2);
std::cout << std::this_thread::get_id() << ": " << g_i << '\n';
for (std::vector<int>::const_iterator i = test.begin(); i != test.end(); ++i)
std::cout << std::this_thread::get_id() << " thread vector: " << *i << '\n';
// g_i_mutex is automatically released when lock
// goes out of scope
}
void request_threadedvar()
{
for (std::vector<int>::const_iterator i = test.begin(); i != test.end(); ++i)
std::cout << std::this_thread::get_id() << " request threaded vector: " << *i << '\n';
}
int main()
{
std::cout << "main: " << g_i << '\n';
test.resize(test.size() + 1, 1);
for (std::vector<int>::const_iterator i = test.begin(); i != test.end(); ++i)
std::cout << "main vector: " << *i << '\n';
std::thread t1(safe_increment);
request_threadedvar();
std::thread t2(safe_increment);
t1.join();
t2.join();
std::cout << "main: " << g_i << '\n';
for (std::vector<int>::const_iterator i = test.begin(); i != test.end(); ++i)
std::cout << "main vector: " << *i << '\n';
}
【问题讨论】:
-
如果任何线程正在写入共享数据,则对该共享数据的任何读取都会遇到竞争条件。所以,是的,
main()函数和“读取函数”需要使用互斥锁,如果至少有一个(潜在的)活动写入器。如果保证没有主动写入而只进行读取(例如,写入器在任何读取器线程开始之前终止,并且不再创建写入器),则读取器不需要同步。
标签: c++ multithreading vector thread-safety