Skip to content

Instantly share code, notes, and snippets.

@hooddanielc
Created August 28, 2018 05:06
Show Gist options
  • Save hooddanielc/0a30c454b71179521f936f8ffa21a8b0 to your computer and use it in GitHub Desktop.
Save hooddanielc/0a30c454b71179521f936f8ffa21a8b0 to your computer and use it in GitHub Desktop.
Block until C++ object is destroyed
#pragma once
struct promise_t {
bool fullfilled;
std::mutex *mutex;
std::condition_variable *condition_variable;
promise_t(std::mutex *mutex_, std::condition_variable *condition_variable_):
mutex(mutex_),
condition_variable(condition_variable_),
fullfilled(false) {}
// the calling thread waits
void wait() {
std::unique_lock<std::mutex> lock(*mutex);
while (!fullfilled) {
condition_variable->wait(lock);
}
}
// the consuming thread resolves
void resolve() {
std::unique_lock<std::mutex> lock(*mutex);
fullfilled = true;
condition_variable->notify_one();
}
};
class promise_event_t: public generic_event_t {
public:
promise_event_t(
event_type_t type,
std::shared_ptr<promise_t> promise_
):
generic_event_t(type),
promise(promise_) {}
virtual ~promise_event_t() {
LOGV("DESTROY");
promise->resolve();
}
private:
std::shared_ptr<promise_t> promise;
};
std::queue<std::shared_ptr<promise_event_t>> some_queue;
int main(int, char*[]) {
auto promise = std::make_shared<promise_t>(&mutex, &condition_variable);
{
auto app = android_wrapper_t::unwrap(activity);
auto event = std::make_shared<promise_event_t>(unknown, promise);
some_queue.push(event);
}
// wait until another thread pops from queue and destroys event
promise->wait();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment