在C++中,可以使用線程安全的數據結構和同步機制來確保多線程環境下的filter操作的安全性。以下是一些常見的方法:
#include <iostream>
#include <vector>
#include <mutex>
#include <algorithm>
std::mutex mtx;
void filter(std::vector<int>& data, int threshold) {
std::lock_guard<std::mutex> lock(mtx);
data.erase(std::remove_if(data.begin(), data.end(), [threshold](int i) { return i < threshold; }), data.end());
}
int main() {
std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int threshold = 5;
std::thread t1(filter, std::ref(data), threshold);
std::thread t2(filter, std::ref(data), threshold);
t1.join();
t2.join();
for (int i : data) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
#include <iostream>
#include <vector>
#include <atomic>
#include <algorithm>
std::atomic<int> threshold(5);
void filter(std::vector<int>& data) {
for (auto it = data.begin(); it != data.end();) {
if (*it < threshold) {
it = data.erase(it);
} else {
++it;
}
}
}
int main() {
std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::thread t1(filter, std::ref(data));
std::thread t2(filter, std::ref(data));
t1.join();
t2.join();
for (int i : data) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
#include <iostream>
#include <vector>
#include <algorithm>
thread_local int threshold = 5;
void filter(std::vector<int>& data) {
data.erase(std::remove_if(data.begin(), data.end(), [](int i) { return i < threshold; }), data.end());
}
int main() {
std::vector<int> data = {1, 2, 3, 4, 5, 6, 7, 8, 9};
std::thread t1(filter, std::ref(data));
std::thread t2(filter, std::ref(data));
t1.join();
t2.join();
for (int i : data) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
這些方法可以幫助確保在多線程環境下的filter操作的安全性,但需要根據具體的情況選擇適合的方法來處理。