Skip to content

Instantly share code, notes, and snippets.

@George3d6
Last active September 18, 2018 21:24
Show Gist options
  • Save George3d6/450c5ae7b7cc39e92c231fbe3c6fb7a0 to your computer and use it in GitHub Desktop.
Save George3d6/450c5ae7b7cc39e92c231fbe3c6fb7a0 to your computer and use it in GitHub Desktop.
//The header of Widget (the important bits for us)
class Widget {
public:
void lock_widget_mutex();
void unlock_widget_mutex();
int get_status() const;
void trigger_event();
}
//A function which gives us pointers to these Widgets
Widget* get_widget();
//Now lets see how we use this library
//Lets assume we want to use the widget is it's status is 42
void use_widget() {
auto widget_ptr = get_widget();
if(widget_ptr->get_status() == 42)
widget_ptr->trigger_event();
}
//That might be a valid way to use our pointer to a widget, here's another one:
void use_widget() {
auto widget_ptr = get_widget();
//Lock the widget since other threads might also be trying to use it
widget_ptr->lock_widget_mutex();
if(widget_ptr->get_status() == 42)
widget_ptr->trigger_event();
widget_ptr->unlock_widget_mutex();
}
// And here's another totally valid way to use it:
void use_widget() {
auto widget_ptr = get_widget();
//Maybe thge widget is unavailable so we should try getting it again
while(widget_ptr == nullptr) {
auto widget_ptr = get_widget();
}
if(widget_ptr->get_status() == 42)
widget_ptr->trigger_event();
//We no longer need the widget to lets free it
free(widget_ptr);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment