Код: Выделить всё
#include
using namespace std; // for the sake of minimal reproducible example
template
class ConcurrentVector {
public:
ConcurrentVector() : mMutex{}
, mVector{}
{}
auto begin(){
scoped_lock lk(mMutex);
return mVector.begin();
}
auto end(){
scoped_lock lk(mMutex);
return mVector.end();
}
T& push_back(T t) {
scoped_lock lk(mMutex);
mVector.push_back(move(t));
return mVector.back();
}
void clear() {
scoped_lock lk(mMutex);
mVector.clear();
}
private:
mutex mMutex;
vector mVector;
};
int main(){
ConcurrentVector vec{};
atomic_bool terminate_flag = false;
jthread fill_thread{[&](){
static int i = 0;
while(!terminate_flag){
this_thread::sleep_for(10ms);
vec.push_back(++i);
}
}};
jthread clear_thread{[&](){
while(!terminate_flag){
this_thread::sleep_for(1s);
vec.clear();
}
}};
jthread iterate_thread{[&](){
while(!terminate_flag){
this_thread::sleep_for(400ms);
for(auto i : vec){
cout
Подробнее здесь: [url]https://stackoverflow.com/questions/78734926/lock-based-concurrent-vector[/url]