Views in C++ are not inherently thread-safe. Their thread-safety depends on the underlying container and how it is accessed. Since views do not own the data, any modifications to the underlying container can affect the views derived from it, potentially leading to data races in a multi-threaded context.
Here’s an example using std::mutex
to synchronize access to a container and its view:
#include <iostream>
#include <mutex>
#include <ranges>
#include <thread>
#include <vector>
std::mutex mtx;
void PrintView(const std::vector<int>& Numbers) {
std::lock_guard<std::mutex> lock(mtx);
auto View = std::views::take(Numbers, 3);
for (int Num : View) {
std::cout << Num << ", ";
}
std::cout << "\n";
}
int main() {
std::vector<int> Numbers{1, 2, 3, 4, 5};
std::thread t1(PrintView, std::ref(Numbers));
std::thread t2(PrintView, std::ref(Numbers));
t1.join();
t2.join();
}
1, 2, 3,
1, 2, 3,
std::lock_guard
locks the mutex, ensuring only one thread accesses the view and its underlying container at a time.While views themselves do not add thread-safety, careful management of the underlying container’s access can ensure safe use in multi-threaded applications. Always use synchronization mechanisms like mutexes when modifying shared data to prevent data races and undefined behavior.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to create and use views in C++ using examples from std::views