reduce the number of recheck times for the sleep function

This commit is contained in:
mutouyun 2021-09-20 23:29:30 +08:00
parent 7a536b6e9c
commit f6bd578c8a
2 changed files with 31 additions and 2 deletions

View File

@ -72,7 +72,7 @@ inline void yield(K& k) noexcept {
++k; ++k;
} }
template <std::size_t N = 4096, typename K, typename F> template <std::size_t N = 32, typename K, typename F>
inline void sleep(K& k, F&& f) { inline void sleep(K& k, F&& f) {
if (k < static_cast<K>(N)) { if (k < static_cast<K>(N)) {
std::this_thread::yield(); std::this_thread::yield();
@ -84,7 +84,7 @@ inline void sleep(K& k, F&& f) {
++k; ++k;
} }
template <std::size_t N = 4096, typename K> template <std::size_t N = 32, typename K>
inline void sleep(K& k) { inline void sleep(K& k) {
sleep<N>(k, [] { sleep<N>(k, [] {
std::this_thread::sleep_for(std::chrono::milliseconds(1)); std::this_thread::sleep_for(std::chrono::milliseconds(1));

View File

@ -161,3 +161,32 @@ TEST(Sync, Condition) {
for (auto &t : test_conds) t.join(); for (auto &t : test_conds) t.join();
} }
TEST(Sync, ConditionRobust) {
printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 1\n");
ipc::sync::condition cond {"test-cond"};
printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 2\n");
ipc::sync::mutex lock {"test-mutex"};
printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 3\n");
lock.lock();
std::thread unlock {[] {
printf("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW 1\n");
ipc::sync::condition cond {"test-cond"};
printf("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW 2\n");
ipc::sync::mutex lock {"test-mutex"};
printf("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW 3\n");
{
std::lock_guard<ipc::sync::mutex> guard {lock};
}
std::this_thread::sleep_for(std::chrono::seconds(1));
printf("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW 4\n");
cond.notify();
printf("WWWWWWWWWWWWWWWWWWWWWWWWWWWWWW 5\n");
}};
printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 4\n");
cond.wait(lock);
printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 5\n");
lock.unlock();
printf("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX 6\n");
unlock.join();
}