为什么在多线程操作下,向量的拷贝会崩溃?

huangapple go评论56阅读模式
英文:

Why does the copy of vector crash under multi-threaded operation?

问题

为什么 vector<int> x = v 崩溃而不触发双倍缩放?
我知道这个操作是危险的。但我只想知道为什么它会导致崩溃。

我不知道内部发生了什么。
英文:
#include &lt;vector&gt;
#include &lt;iostream&gt;
#include &lt;thread&gt;

using namespace std;

vector&lt;int&gt; v = { 1 };

int main() {
	v.reserve(100);

	thread t([] {
		while (1) {
			cout &lt;&lt; v.size() &lt;&lt; v.end() - v.begin(); // not crash
			cout &lt;&lt; v[0]; // not crash
			cout &lt;&lt; *v.begin(); // not crash
			cout &lt;&lt; *v.end(); // not crash
			vector&lt;int&gt; x = v; // crash!!
		}
		});

	std::this_thread::sleep_for(std::chrono::milliseconds(1000));

	while (1) {
		for (int i = 0; i &lt; 16; ++i) {
			v.push_back(i);
		}
		for (int i = 0; i &lt; 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.

huangapple
  • 本文由 发表于 2023年2月24日 15:23:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75553620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定