2018-12-31 20:04:05 +01:00
|
|
|
//
|
2021-01-01 13:57:46 +01:00
|
|
|
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
|
2018-12-31 20:04:05 +01:00
|
|
|
//
|
|
|
|
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
|
|
|
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
|
|
|
//
|
2019-02-12 22:26:36 +01:00
|
|
|
#include "td/utils/common.h"
|
2018-12-31 20:04:05 +01:00
|
|
|
#include "td/utils/HazardPointers.h"
|
|
|
|
#include "td/utils/logging.h"
|
|
|
|
#include "td/utils/port/thread.h"
|
|
|
|
#include "td/utils/Random.h"
|
2019-07-23 00:50:12 +02:00
|
|
|
#include "td/utils/Slice.h"
|
2018-12-31 20:04:05 +01:00
|
|
|
#include "td/utils/tests.h"
|
|
|
|
|
|
|
|
#include <atomic>
|
|
|
|
|
|
|
|
#if !TD_THREAD_UNSUPPORTED
|
|
|
|
TEST(HazardPointers, stress) {
|
|
|
|
struct Node {
|
2019-01-24 04:18:14 +01:00
|
|
|
std::atomic<std::string *> name_{nullptr};
|
2018-12-31 20:04:05 +01:00
|
|
|
char pad[64];
|
|
|
|
};
|
|
|
|
int threads_n = 10;
|
|
|
|
std::vector<Node> nodes(threads_n);
|
|
|
|
td::HazardPointers<std::string> hazard_pointers(threads_n);
|
|
|
|
std::vector<td::thread> threads(threads_n);
|
|
|
|
int thread_id = 0;
|
|
|
|
for (auto &thread : threads) {
|
|
|
|
thread = td::thread([&, thread_id] {
|
2019-07-06 13:29:15 +02:00
|
|
|
std::remove_reference_t<decltype(hazard_pointers)>::Holder holder(hazard_pointers, thread_id, 0);
|
2018-12-31 20:04:05 +01:00
|
|
|
for (int i = 0; i < 1000000; i++) {
|
|
|
|
auto &node = nodes[td::Random::fast(0, threads_n - 1)];
|
|
|
|
auto *str = holder.protect(node.name_);
|
|
|
|
if (str) {
|
2019-07-06 13:29:15 +02:00
|
|
|
CHECK(*str == td::Slice("one") || *str == td::Slice("twotwo"));
|
2018-12-31 20:04:05 +01:00
|
|
|
}
|
|
|
|
holder.clear();
|
|
|
|
if (td::Random::fast(0, 5) == 0) {
|
2020-10-08 11:56:08 +02:00
|
|
|
std::string *new_str = new std::string(td::Random::fast_bool() ? "one" : "twotwo");
|
2018-12-31 20:04:05 +01:00
|
|
|
if (node.name_.compare_exchange_strong(str, new_str, std::memory_order_acq_rel)) {
|
|
|
|
hazard_pointers.retire(thread_id, str);
|
|
|
|
} else {
|
|
|
|
delete new_str;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
thread_id++;
|
|
|
|
}
|
|
|
|
for (auto &thread : threads) {
|
|
|
|
thread.join();
|
|
|
|
}
|
2021-10-07 15:56:45 +02:00
|
|
|
LOG(INFO) << "Undeleted pointers: " << hazard_pointers.to_delete_size_unsafe();
|
2018-12-31 20:04:05 +01:00
|
|
|
CHECK(static_cast<int>(hazard_pointers.to_delete_size_unsafe()) <= threads_n * threads_n);
|
|
|
|
for (int i = 0; i < threads_n; i++) {
|
|
|
|
hazard_pointers.retire(i);
|
|
|
|
}
|
|
|
|
CHECK(hazard_pointers.to_delete_size_unsafe() == 0);
|
|
|
|
}
|
|
|
|
#endif //!TD_THREAD_UNSUPPORTED
|