How do I serialize and deserialize contents with std::vector in multithreaded code?

To serialize and deserialize contents of a `std::vector` in multithreaded C++ code, you need to ensure thread safety when accessing shared resources. You can use mutexes or other synchronization mechanisms to protect the shared data. Below is an example demonstrating how to serialize and deserialize a `std::vector` while safely managing concurrent access.

Keywords: C++, std::vector, serialization, deserialization, multithreaded, thread safety, mutex, example
Description: This example illustrates how to safely serialize and deserialize a std::vector in a multithreaded C++ application using mutexes for synchronization.
#include <iostream> #include <vector> #include <sstream> #include <mutex> #include <thread> std::mutex mtx; // Mutex for synchronizing access to vector std::vector myVector; // Serialize the vector into a string std::string serialize() { std::lock_guard<std::mutex> lock(mtx); std::ostringstream oss; for (const auto& item : myVector) { oss << item << " "; } return oss.str(); } // Deserialize the string back into the vector void deserialize(const std::string& data) { std::lock_guard<std::mutex> lock(mtx); myVector.clear(); std::istringstream iss(data); int item; while (iss >> item) { myVector.push_back(item); } } // Example function that modifies the vector void modifyVector() { std::lock_guard<std::mutex> lock(mtx); myVector.push_back(rand() % 100); // Add random number to the vector } int main() { std::thread t1(modifyVector); std::thread t2(modifyVector); t1.join(); t2.join(); std::string serialized = serialize(); std::cout << "Serialized Vector: " << serialized << std::endl; deserialize(serialized); std::cout << "Deserialized Vector size: " << myVector.size() << std::endl; return 0; }

Keywords: C++ std::vector serialization deserialization multithreaded thread safety mutex example