Browse Source

need a semaphore here

synchronous
Volker Birk 5 years ago
parent
commit
2ecdb94ba6
  1. 39
      Semaphore.hh
  2. 28
      callback_dispatcher.cc
  3. 4
      callback_dispatcher.hh

39
Semaphore.hh

@ -0,0 +1,39 @@
#include <mutex>
#include <condition_variable>
namespace pEp {
class Semaphore {
public:
Semaphore() : _stop(false) {}
void stop()
{
std::unique_lock<std::mutex> lock(mtx);
_stop = true;
}
void try_wait()
{
std::unique_lock<std::mutex> lock(mtx);
if (!_stop)
return;
while(_stop){
cv.wait(lock);
}
}
void go()
{
std::unique_lock<std::mutex> lock(mtx);
_stop = false;
cv.notify_all();
}
private:
std::mutex mtx;
std::condition_variable cv;
bool _stop;
};
}

28
callback_dispatcher.cc

@ -30,11 +30,8 @@ namespace pEp {
targets.push_back({messageToSend, notifyHandshake, on_startup, shutdown});
if (!Adapter::on_sync_thread()) {
// try_unlock() possibly waiting messageToSend
sync_mtx.try_lock();
sync_mtx.unlock();
}
if (!Adapter::on_sync_thread())
semaphore.go();
}
void CallbackDispatcher::remove(::messageToSend_t messageToSend)
@ -71,9 +68,7 @@ namespace pEp {
void CallbackDispatcher::start_sync()
{
// try_unlock()
callback_dispatcher.sync_mtx.try_lock();
callback_dispatcher.sync_mtx.unlock();
callback_dispatcher.semaphore.go();
pEp::Adapter::startup<CallbackDispatcher>(CallbackDispatcher::messageToSend,
CallbackDispatcher::notifyHandshake, &callback_dispatcher,
@ -88,10 +83,7 @@ namespace pEp {
void CallbackDispatcher::stop_sync()
{
// try_unlock()
callback_dispatcher.sync_mtx.try_lock();
callback_dispatcher.sync_mtx.unlock();
callback_dispatcher.semaphore.go();
pEp::Adapter::shutdown();
for (auto target : callback_dispatcher.targets) {
@ -103,21 +95,17 @@ namespace pEp {
PEP_STATUS CallbackDispatcher::_messageToSend(::message *msg)
{
if (Adapter::on_sync_thread() && !msg) {
semaphore.try_wait();
PEP_STATUS status = PassphraseCache::messageToSend(passphrase_cache, Adapter::session());
// if the cache has no valid passphrase ask the app
if (status == PEP_PASSPHRASE_REQUIRED || status == PEP_WRONG_PASSPHRASE) {
// lock mutex and call async
sync_mtx.lock();
notifyHandshake(nullptr, nullptr, SYNC_PASSPHRASE_REQUIRED);
// wait() until mutex was unlocked by add()
sync_mtx.lock();
sync_mtx.unlock();
semaphore.stop();
}
// the pEp engine must try again
return PEP_STATUS_OK;
return status;
}
for (auto target : targets) {

4
callback_dispatcher.hh

@ -4,6 +4,7 @@
#include <functional>
#include <mutex>
#include "Adapter.hh"
#include "Semaphore.hh"
namespace pEp {
// use this class when implementing a desktop adapter
@ -21,8 +22,7 @@ namespace pEp {
proc on_shutdown;
};
std::vector<callbacks> targets;
std::mutex sync_mtx;
Semaphore semaphore;
public:
void add(

Loading…
Cancel
Save