std::stringstream
本身并不是線程安全的
為了在多線程環(huán)境中使用 std::stringstream
,你可以采取以下措施:
std::stringstream
實(shí)例。這樣,每個(gè)線程都有自己的緩沖區(qū)和狀態(tài),從而避免了競爭條件。這種方法的缺點(diǎn)是可能會消耗更多內(nèi)存。#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
實(shí)例的訪問。這種方法的缺點(diǎn)是可能會導(dǎo)致性能下降,因?yàn)榫€程需要等待鎖釋放。#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;
}
總之,在多線程環(huán)境中使用 std::stringstream
時(shí),請確保正確處理線程安全問題??梢酝ㄟ^為每個(gè)線程提供獨(dú)立的實(shí)例或使用同步機(jī)制來實(shí)現(xiàn)。