Skip to content

Instantly share code, notes, and snippets.

@lethee
Created April 4, 2016 06:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lethee/f76d1e297f14b97179e08f2e609c3cdd to your computer and use it in GitHub Desktop.
Save lethee/f76d1e297f14b97179e08f2e609c3cdd to your computer and use it in GitHub Desktop.
glib main roop, boot coroutine, blocking loop
// g++ -std=c++11 -I/usr/include/glib-2.0 -I/usr/lib/i386-linux-gnu/glib-2.0/include main.cpp -lglib-2.0 -lboost_system -lboost_coroutine -lboost_context -o test
//
#include <iostream>
#include <thread>
#include <chrono>
#include <glib.h>
#include <boost/coroutine/all.hpp>
using namespace std;
using namespace boost::coroutines;
GMainLoop *loop = NULL;
gboolean fnTimer(gpointer user_data)
{
static int count = 0;
cout << "fnTimer: " << count++ << endl;
if (count == 5) {
g_main_loop_quit(loop);
}
return true;
}
void fnCoro(coroutine<void>::push_type & yield)
{
static int count = 0;
while (true) {
this_thread::sleep_for(chrono::milliseconds(1000));
cout << "coro " << count++ << endl;
yield();
}
}
int main(void)
{
coroutine<void>::pull_type coro{fnCoro};
coro();
coro();
coro();
coro();
for (int i = 0; i < 5; i++) {
this_thread::sleep_for(chrono::milliseconds(1000));
cout << "step" << endl;
}
loop = g_main_loop_new(NULL, false);
GSource *src = g_timeout_source_new(1000);
g_source_set_callback(src, fnTimer, NULL, NULL);
g_source_attach(src, g_main_loop_get_context(loop));
g_source_unref(src);
g_main_loop_run(loop);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment