开了几个线程跑,没发现问题
template <typename T> struct LocklessCache {
std::atomic<T *> caches[4];
T *get() {
for (auto &o : caches) {
if (T *t = o.exchange(nullptr, std::memory_order_acq_rel))
return t;
}
return new T();
}
void release(T *t) {
for (auto &o : caches) {
t = o.exchange(t, std::memory_order_acq_rel);
if (t == nullptr)
return;
}
delete t;
}
};
LocklessCache<int> cache;
int main(int argc, char **argv) {
std::thread *threads[8];
for (size_t k = 0; k < _countof(threads); ++k) {
threads[k] = new std::thread([]() {
for (size_t k = 0; k < 1000000000; k++) {
auto p = cache.get();
//Sleep(1);
cache.release(p);
}
});
}
for (size_t k = 0; k < _countof(threads); ++k) {
threads[k]->join();
delete threads[k];
}
--
FROM 221.218.167.*