#!/usr/bin/perl
use strict;
use warnings;
use threads;
use Glib;
use Queue;

=head1 Signaling across threads to a Glib loop

Looks like the best way is to use a pipe

=cut

my $q=Glib::Thread::Queue->new();
my $q2=Glib::Thread::Queue->new();

threads->create(
    sub{
        print "sleeping\n";
        sleep 2;
        print "sending boo\n";
        $q->enqueue('boo');
        sleep 2;
        threads->create(
            sub{
                print "inserting bar & foo\n";
                $q->insert(0,'bar');
                $q->insert(1,'foo');
                print "signaling\n";
                $q->signal();
                print "signaling\n";
                $q->signal();
            });
        sleep 2;
        print "waiting for command\n";
        my $cmd=$q2->dequeue;
        print "got $cmd\n";
        print "sending quit";
        $q->enqueue('quit');
});

my $loop=Glib::MainLoop->new();
$q->add_watch(sub{
                  print "waking up\n";
                  my $foo=$q->dequeue();
                  print "got $foo\n";
                  if ($foo eq 'quit') {
                      print "quitting\n";
                      $loop->quit;
                  }
                  elsif ($foo eq 'foo') {
                      print "sending command\n";
                      $q2->enqueue('the command');
                      print "sent command\n";
                  }
                  return Glib::SOURCE_CONTINUE;
              },
          );
$loop->run;
