修正 recv timeout 接口cpu占用过高的问题

This commit is contained in:
mutouyun 2021-09-16 23:49:01 +08:00
parent d80bea9b5d
commit baf645eea1
2 changed files with 12 additions and 5 deletions

View File

@ -224,8 +224,6 @@ public:
static bool wait(handle_t h, std::size_t tm = invalid_value) { static bool wait(handle_t h, std::size_t tm = invalid_value) {
if (h == invalid()) return false; if (h == invalid()) return false;
switch (tm) { switch (tm) {
case 0:
return true;
case invalid_value: case invalid_value:
IPC_SEMAPHORE_FUNC_(sem_wait, h); IPC_SEMAPHORE_FUNC_(sem_wait, h);
default: { default: {

View File

@ -13,7 +13,7 @@ namespace detail {
struct waiter_helper { struct waiter_helper {
struct wait_counter { struct wait_counter {
std::atomic<unsigned> waiting_ { 0 }; std::atomic<long> waiting_ { 0 };
long counter_ = 0; long counter_ = 0;
}; };
@ -40,7 +40,7 @@ struct waiter_helper {
{ {
IPC_UNUSED_ auto guard = ctrl.get_lock(); IPC_UNUSED_ auto guard = ctrl.get_lock();
if (!std::forward<F>(pred)()) return true; if (!std::forward<F>(pred)()) return true;
counter.counter_ += 1; counter.counter_ = counter.waiting_.load(std::memory_order_relaxed);
} }
mtx.unlock(); mtx.unlock();
@ -69,6 +69,11 @@ struct waiter_helper {
return ret; return ret;
} }
template <typename Ctrl>
static void clear_handshake(Ctrl & ctrl) {
while (ctrl.handshake_wait(0)) ;
}
template <typename Ctrl> template <typename Ctrl>
static bool notify(Ctrl & ctrl) { static bool notify(Ctrl & ctrl) {
auto & counter = ctrl.counter(); auto & counter = ctrl.counter();
@ -77,6 +82,7 @@ struct waiter_helper {
} }
bool ret = true; bool ret = true;
IPC_UNUSED_ auto guard = ctrl.get_lock(); IPC_UNUSED_ auto guard = ctrl.get_lock();
clear_handshake(ctrl);
if (counter.counter_ > 0) { if (counter.counter_ > 0) {
ret = ctrl.sema_post(1); ret = ctrl.sema_post(1);
counter.counter_ -= 1; counter.counter_ -= 1;
@ -93,11 +99,13 @@ struct waiter_helper {
} }
bool ret = true; bool ret = true;
IPC_UNUSED_ auto guard = ctrl.get_lock(); IPC_UNUSED_ auto guard = ctrl.get_lock();
clear_handshake(ctrl);
if (counter.counter_ > 0) { if (counter.counter_ > 0) {
ret = ctrl.sema_post(counter.counter_); ret = ctrl.sema_post(counter.counter_);
auto tm = default_timeout / counter.counter_;
do { do {
counter.counter_ -= 1; counter.counter_ -= 1;
ret = ret && ctrl.handshake_wait(default_timeout); ret = ret && ctrl.handshake_wait(tm);
} while (counter.counter_ > 0); } while (counter.counter_ > 0);
} }
return ret; return ret;
@ -116,6 +124,7 @@ struct waiter_helper {
} }
bool ret = true; bool ret = true;
IPC_UNUSED_ auto guard = ctrl.get_lock(); IPC_UNUSED_ auto guard = ctrl.get_lock();
clear_handshake(ctrl);
if (counter.counter_ > 0) { if (counter.counter_ > 0) {
ret = ctrl.sema_post(counter.counter_); ret = ctrl.sema_post(counter.counter_);
counter.counter_ -= 1; counter.counter_ -= 1;