Yes, you can use std::string_view
in multithreaded applications, but you need to be cautious about the thread safety of the underlying string.
std::string_view
itself is just a non-owning, read-only view, so its safety depends entirely on the lifecycle and access patterns of the string it views.
If the underlying string is immutable or only accessed in a read-only fashion across multiple threads, using std::string_view
is safe. Here's an example:
#include <iostream>
#include <string>
#include <string_view>
#include <thread>
void printStringView(std::string_view sv) {
std::cout << sv << '\n';
}
int main() {
std::string str{"Hello, multithreading world"};
std::string_view view{str};
std::thread t1(printStringView, view);
std::thread t2(printStringView, view);
t1.join();
t2.join();
}
Hello, multithreading world
Hello, multithreading world
In this example, str
is not modified after the std::string_view
is created, making it safe to use in multiple threads.
If the underlying string is modified by one thread while another thread accesses it through a std::string_view
, it can lead to undefined behavior. You must synchronize access to ensure safety:
#include <iostream>
#include <string>
#include <string_view>
#include <thread>
#include <mutex>
std::mutex mtx;
void printStringView(std::string_view sv) {
std::lock_guard<std::mutex> lock(mtx);
std::cout << sv << '\n';
}
int main() {
std::string str{"Hello, multithreading world"};
std::string_view view{str};
std::thread t1(printStringView, view);
// Ensure t1 completes before proceeding to t2
t1.join();
std::thread t2([&str, &view]() {
std::lock_guard<std::mutex> lock(mtx);
str = "New content";
view = str;
std::cout << view << '\n';
});
t2.join();
}
Hello, multithreading world
New content
std::string_view
can be used in multithreaded applications as long as you ensure the underlying string is accessed safely.
Use synchronization mechanisms like mutexes when the string can be modified by multiple threads, or ensure it remains immutable for read-only access across threads.
Answers to questions are automatically generated and may not have been reviewed.
A practical introduction to string views, and why they should be the main way we pass strings to functions