阅读量:137
std::stringstream 本身并不是线程安全的
为了在多线程环境中使用 std::stringstream,你可以采取以下措施:
- 为每个线程创建一个单独的
std::stringstream实例。这样,每个线程都有自己的缓冲区和状态,从而避免了竞争条件。这种方法的缺点是可能会消耗更多内存。
#include
#include
#include
#include
void process(int id) {
std::stringstream ss;
ss << "Thread " << id class="hljs-string">" is processing."<< std class="hljs-built_in">str();
}
int main() {
const int num_threads = 5;
std::vector threads;
for (int i = 0; i < num class="hljs-built_in">emplace_back(process, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}
- 使用互斥锁(如
std::mutex)来同步对共享std::stringstream实例的访问。这种方法的缺点是可能会导致性能下降,因为线程需要等待锁释放。
#include
#include
#include
#include
#include
std::mutex mtx;
std::stringstream ss;
void process(int id) {
std::unique_lock lock(mtx) ;
ss << "Thread " << id class="hljs-string">" is processing."<< std class="hljs-built_in">unlock();
std::cout << ss class="hljs-built_in">str();
}
int main() {
const int num_threads = 5;
std::vector threads;
for (int i = 0; i < num class="hljs-built_in">emplace_back(process, i);
}
for (auto& t : threads) {
t.join();
}
return 0;
}
总之,在多线程环境中使用 std::stringstream 时,请确保正确处理线程安全问题。可以通过为每个线程提供独立的实例或使用同步机制来实现。