C++20 coroutines with std::vector causing unexpected memory issues when resizing
I'm migrating some code and I'm working with C++20 coroutines and I've run into some strange behavior when using `std::vector`. I have a function that launches multiple coroutines which each attempt to use a shared `std::vector`. The issue arises when I try to resize the vector while the coroutines are still using it. I believe this is causing memory-related issues, but I'm not sure how to handle it properly. Here's a simplified version of what I have: ```cpp #include <iostream> #include <vector> #include <coroutine> #include <thread> struct Task { struct promise_type { Task get_return_object() { return {}; } std::suspend_always initial_suspend() { return {}; } std::suspend_always final_suspend() noexcept { return {}; } void unhandled_exception() { std::terminate(); } void return_void() {} }; }; std::vector<int> sharedVector; Task coroutineFunc(int id) { for (int i = 0; i < 5; ++i) { std::cout << "Coroutine " << id << " reading: " << sharedVector[i] << '\n'; co_await std::suspend_always{}; } } void resizeVector() { sharedVector.resize(10); } int main() { for (int i = 0; i < 3; ++i) { std::thread([=] { coroutineFunc(i); }).detach(); } resizeVector(); std::this_thread::sleep_for(std::chrono::seconds(1)); return 0; } ``` When I run this, I sometimes get a crash or a segmentation fault, and I suspect that itโs due to `resizeVector` being called while the coroutines are trying to access `sharedVector`. I've tried adding locks around the vector accesses, but that makes the performance worse and doesn't fully resolve the crashing. Whatโs the best way to safely manage resizing a `std::vector` thatโs being accessed by coroutines concurrently? Any suggestions on best practices to avoid these memory issues would be appreciated. I'm using GCC 10.2 and CMake for building my project. I'm using C++ 3.11 in this project.