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


