threads - Re: how to catch the SIG within detached threads

Posted on Thu Apr 5 13:09:59 2007 by calli in response to 4756 (See the whole thread of 8)
Re: how to catch the SIG within detached threads
Well,
your program works, but if I change it that way,
that SIGs from 'outside' should force the thread-sleep to break
--- this fails:
#!/usr/bin/perl use strict; use warnings; $| = 1; use threads; our ($thr1,$thr2); sub thr1 { my $term = 0; $SIG{USR1} = sub { print("\tthr1 caught SIGUSR1\n"); $term = 1; }; while (! $term) { print("\tthr1 sleeping...\n"); sleep 100; print("\tthr1 woke up\n"); } print("\tthr1 done\n"); } sub thr2 { my $term = 0; $SIG{USR1} = sub { print("\t\tthr2 caught SIGUSR1\n"); $term = 1; }; while (! $term) { print("\t\tthr2 sleeping...\n"); sleep 100; print("\t\tthr2 woke up\n"); } print("\t\tthr2 done\n"); } $SIG{INT} = sub { print("Ignoring SIGINT\n"); print("\nSignalling thr1...\n"); $thr1->kill('USR1'); sleep(1); print("\nSignalling thr2...\n"); $thr2->kill('USR1'); sleep(1); print("Waking up threads...\n"); $SIG{INT} = 'DEFAULT'; kill('INT', $$); sleep(2); }; MAIN: { print("$$: Starting threads...\n"); $thr1 = threads->create('thr1'); $thr2 = threads->create('thr2'); $thr1->detach(); $thr2->detach(); while ( 1 ) { sleep 1; } } # SIGINT is used to wake up threads print("\nDone\n"); exit(0);
This produces after I typed kill -INT 8701:
8701: Starting threads... thr1 sleeping... thr2 sleeping... Ignoring SIGINT Signalling thr1... Signalling thr2... Waking up threads...

Now all, Mum and her 2 threads are dead, the threads died without a sigh :(
Carl
Direct Responses: 4768 | Write a response