Skip to content

Commit

Permalink
Merge tag 'thread_urgent-2023-03-16' of https://github.com/alviroiska…
Browse files Browse the repository at this point in the history
…ndar/GNUWeebBot2

Pull a single commit for core/thread from Alviro:

A single commit to make the cond_wait() function more efficient:

  - Don't unlock-relock in cond_wait().

* tag 'thread_urgent-2023-03-16' of https://github.com/alviroiskandar/GNUWeebBot2:
  core/thread: Don't unlock-relock in cond_wait()

Link: https://lore.gnuweeb.org/gwml/20230316052910.3830231-1-alviro.iskandar@gnuweeb.org
Signed-off-by: Ammar Faizi <ammarfaizi2@gnuweeb.org>
  • Loading branch information
ammarfaizi2 committed Mar 16, 2023
2 parents bf0bf94 + 2dadec2 commit 53f76b7
Showing 1 changed file with 24 additions and 13 deletions.
37 changes: 24 additions & 13 deletions core/thread.cc
Expand Up @@ -88,7 +88,8 @@ struct thread_struct {
};

struct mutex_struct {
std::mutex mutex;
std::mutex mutex;
std::unique_lock<std::mutex> *ulock;
};

struct cond_struct {
Expand Down Expand Up @@ -157,7 +158,18 @@ int mutex_lock(struct mutex_struct **m)

int mutex_unlock(struct mutex_struct **m)
{
(*m)->mutex.unlock();
std::unique_lock<std::mutex> *ulock;

ulock = (*m)->ulock;
if (ulock) {
(*m)->ulock = nullptr;
ulock->unlock();
delete ulock;
return 0;
} else {
(*m)->mutex.unlock();
}

return 0;
}

Expand All @@ -181,20 +193,19 @@ int cond_init(struct cond_struct **c)
return 0;
}

static int __cond_wait(struct cond_struct *c, struct mutex_struct *m)
{
std::unique_lock<std::mutex> lock(m->mutex, std::adopt_lock);
c->cond.wait(lock);
return 0;
}

int cond_wait(struct cond_struct **c, struct mutex_struct **m)
{
int ret;
std::unique_lock<std::mutex> *ulock;

ulock = new(std::nothrow)
std::unique_lock<std::mutex>((*m)->mutex,
std::adopt_lock);
if (!ulock)
return -ENOMEM;

ret = __cond_wait(*c, *m);
mutex_lock(m);
return ret;
(*m)->ulock = ulock;
(*c)->cond.wait(*ulock);
return 0;
}

int cond_signal(struct cond_struct **c)
Expand Down

0 comments on commit 53f76b7

Please sign in to comment.