1b39c5158Smillertuse strict; 2b39c5158Smillertuse warnings; 3b39c5158Smillert 4b39c5158SmillertBEGIN { 5b39c5158Smillert use Config; 6b39c5158Smillert if (! $Config{'useithreads'}) { 7b39c5158Smillert print("1..0 # SKIP Perl not compiled with 'useithreads'\n"); 8b39c5158Smillert exit(0); 9b39c5158Smillert } 10b39c5158Smillert} 11b39c5158Smillert 12b39c5158Smillertuse threads; 13b39c5158Smillertuse threads::shared; 14b39c5158Smillertuse Thread::Semaphore; 15b39c5158Smillert 16b39c5158Smillertif ($] == 5.008) { 17*9f11ffb7Safresh1 require './t/test.pl'; # Test::More work-alike for Perl 5.8.0 18b39c5158Smillert} else { 19b39c5158Smillert require Test::More; 20b39c5158Smillert} 21b39c5158SmillertTest::More->import(); 22b39c5158Smillertplan('tests' => 10); 23b39c5158Smillert 24b39c5158Smillert### Basic usage with multiple threads ### 25b39c5158Smillert 26b39c5158Smillertmy $sm = Thread::Semaphore->new(); 27b39c5158Smillertmy $st = Thread::Semaphore->new(0); 28b39c5158Smillertok($sm, 'New Semaphore'); 29b39c5158Smillertok($st, 'New Semaphore'); 30b39c5158Smillert 31b39c5158Smillertmy $token :shared = 0; 32b39c5158Smillert 33b8851fccSafresh1my @threads; 34b8851fccSafresh1 35b8851fccSafresh1push @threads, threads->create(sub { 36b39c5158Smillert $st->down(); 37b39c5158Smillert is($token++, 1, 'Thread 1 got semaphore'); 38b39c5158Smillert $sm->up(); 39b39c5158Smillert 40b39c5158Smillert $st->down(4); 41b39c5158Smillert is($token, 5, 'Thread 1 done'); 42b39c5158Smillert $sm->up(); 43b8851fccSafresh1}); 44b39c5158Smillert 45b8851fccSafresh1push @threads, threads->create(sub { 46b39c5158Smillert $st->down(2); 47b39c5158Smillert is($token++, 3, 'Thread 2 got semaphore'); 48b39c5158Smillert $sm->up(); 49b39c5158Smillert 50b39c5158Smillert $st->down(4); 51b39c5158Smillert is($token, 5, 'Thread 2 done'); 52b39c5158Smillert $sm->up(); 53b8851fccSafresh1}); 54b39c5158Smillert 55b39c5158Smillert$sm->down(); 56b39c5158Smillertis($token++, 0, 'Main has semaphore'); 57b39c5158Smillert$st->up(); 58b39c5158Smillert 59b39c5158Smillert$sm->down(); 60b39c5158Smillertis($token++, 2, 'Main got semaphore'); 61b39c5158Smillert$st->up(2); 62b39c5158Smillert 63b39c5158Smillert$sm->down(); 64b39c5158Smillertis($token++, 4, 'Main re-got semaphore'); 65b39c5158Smillert$st->up(9); 66b39c5158Smillert 67b39c5158Smillert$sm->down(2); 68b39c5158Smillert$st->down(); 69b39c5158Smillert 70b8851fccSafresh1$_->join for @threads; 71b8851fccSafresh1 72*9f11ffb7Safresh1ok(1, 'Main done'); 73*9f11ffb7Safresh1 74b39c5158Smillertexit(0); 75b39c5158Smillert 76b39c5158Smillert# EOF 77