Created
February 24, 2020 17:37
-
-
Save cbecker/08d67df5d9f25c326531cbf20c40282a to your computer and use it in GitHub Desktop.
sigslot example w/shared_ptr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <thread> | |
#include <atomic> | |
#include <cstdio> | |
#include <chrono> | |
#include <memory> | |
#include <sigslot/signal.hpp> | |
/// | |
/// Example with a ImageSource class that provides a imageSignal signal | |
/// That signal is connected to a slot in a WebServer instance, to receive 'images' | |
/// | |
/// sigslot can keep track of objects' lifetime if they're shared_ptrs | |
/// | |
class Thread | |
{ | |
public: | |
Thread() = default; | |
virtual ~Thread() | |
{ | |
if (m_thread.joinable()) | |
m_thread.join(); | |
} | |
virtual void run() = 0; | |
void start() | |
{ | |
m_thread = std::move(std::thread(&Thread::run, this)); | |
} | |
void join() | |
{ | |
m_thread.join(); | |
} | |
private: | |
std::thread m_thread; | |
}; | |
class ImageSource : public Thread | |
{ | |
public: | |
ImageSource() = default; | |
void run() override | |
{ | |
using namespace std::chrono_literals; | |
int i; | |
while(true) | |
{ | |
printf("ImageSource: emitting signal!\n"); | |
std::this_thread::sleep_for(0.5s); | |
imageSignal(i++); | |
if (i == 5) | |
return; | |
} | |
} | |
sigslot::signal<int> imageSignal; | |
}; | |
class WebServer | |
{ | |
public: | |
WebServer() = default; | |
void updateImage(int v) | |
{ | |
printf("Web server: got image %d\n", v); | |
} | |
}; | |
int main() | |
{ | |
auto imageSource = std::make_shared<ImageSource>(); | |
auto webServer = std::make_shared<WebServer>(); | |
imageSource->imageSignal.connect(&WebServer::updateImage, webServer); | |
imageSource->start(); | |
// we delete the slot in webServer and see how the library manages automatic disconnection | |
using namespace std::chrono_literals; | |
std::this_thread::sleep_for(1.1s); | |
webServer.reset(); | |
// this will happen much later | |
imageSource->join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment