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

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