STL icon indicating copy to clipboard operation
STL copied to clipboard

<vector>: Unexpected Behavior with std::vector in Multi-threaded Context

Open eiytoq opened this issue 1 year ago • 1 comments

Describe the bug

Run the code below. The program prints 0.

Curiously, when I replace std::vector with std::list, it works normally and prints 10.

Command-line test case

#include <thread>
#include <print>
#include <vector>

struct A
{
	std::jthread thread;
	std::vector<std::int32_t> vec;

	void threadFunc()
	{
		std::println("{}", vec.size());
	}

	void init()
	{
		vec.resize(10);
		thread = std::jthread(&A::threadFunc, this);
	}
};

int main()
{
	A a;
	a.init();
}

Expected behavior

The program should print 10, as it does with clang and gcc.

STL version

Microsoft Visual Studio Community 2022 - Preview Version 17.13.0 Preview 4.0

eiytoq avatar Feb 03 '25 00:02 eiytoq

Since std::jthread thread; is earlier declared data member than std::vector<std::int32_t> vec;, thread is created earlier, and destroyed later. Later destruction may cause vec.size() to be called on a destroyed vector or vector being concurrently destroyed, so it is undefined behavior.

Other implementation might not bother tampering with destroyed vector, but MSVC apparently happen to do this in debug mode.

You'd better avoid such pattern, but then you resort to is, make sure that either threads are last data member:

struct A
{
	std::vector<std::int32_t> vec;
	std::jthread thread;
       ...
};

or they are explicitly joined before any other objects they may need destroyed:

struct A
{
	std::jthread thread;
	std::vector<std::int32_t> vec;
       
       ~A() { thread.join(); }`
};

Applying either of the changes or both should make MSVC print 10 consistently.

AlexGuteniev avatar Feb 03 '25 09:02 AlexGuteniev