英文:
Why does the copy of vector crash under multi-threaded operation?
问题
为什么 vector<int> x = v 崩溃而不触发双倍缩放?
我知道这个操作是危险的。但我只想知道为什么它会导致崩溃。
我不知道内部发生了什么。
英文:
#include <vector>
#include <iostream>
#include <thread>
using namespace std;
vector<int> v = { 1 };
int main() {
v.reserve(100);
thread t([] {
while (1) {
cout << v.size() << v.end() - v.begin(); // not crash
cout << v[0]; // not crash
cout << *v.begin(); // not crash
cout << *v.end(); // not crash
vector<int> x = v; // crash!!
}
});
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
while (1) {
for (int i = 0; i < 16; ++i) {
v.push_back(i);
}
for (int i = 0; i < 16; ++i) {
v.pop_back();
}
}
t.join();
}
Why does vector<int> x = v crash without triggering double scaling?
I know this operation is dangerous. But I just want to know why it causes crash.
I do not know what happens inside.
答案1
得分: 2
你必须在多个线程同时访问相同的内存且至少有一个线程修改此内存时添加某种同步机制。
英文:
You must add some kind of synchronization mechanism when several threads access the same memory at the same time and at least one thread modify this memory.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论