multithreading - Work with Thread::Semaphore.Limit the number of threads -


i can not deal semapfor. run, passed on 1 stream? in fact, variable $ n randomnaya taken 0 2. when condition $ n = $ (# $ num - stream number), message, flow $ num smokes. others (# $ n! = $ num) should skipped. message "trade not smoke." situation passes threads @ once , not necessary, deduces flow $ num smokes (# in fact gives correct number, not fit situation).

#! usr/bin/perl -w use strict; use warnings; use 5.010; use threads; use threads::shared; use thread::semaphore;   $sem = thread::semaphore->new(1); $n   = int rand(3); $n; $shr : shared = 1; $threads = 2; @threads;  $t ( 0 .. $threads ) {    push @threads, threads->create( \&smoke, $t ); } # Дожидаемся окончания работы всех потоков $t (@threads) { $t->join(); }   sub smoke {    $num = shift;     $sem->down;    "+thread $num started";    sleep 1;    if ( $num = $n ) { sleep 2; "thread $num -- smoke"; }    "-thread $num done. \n";     if ( $num != $n ) {       "-thread $num dont smoke!. \n";    }    { lock($shr); $shr++ }    $sem->up;     return;    sleep 1; } 

semaphores nothing more complicated shared counter.

when call down() counter decreased - , block if cannot. if call up() count incremented. (and blocking released).

however, until 'block' occurs, threads can - , - execute in undefined order, should assume random. (it isn't entirely, relying on particular sequence create race conditions).

it's not complicated, 1 of things can trip buffering - print statements in threads may buffered, appear arrive in strange order.

e.g.:

#! usr/bin/perl -w use strict; use warnings; use 5.010; use threads; use threads::shared; use thread::semaphore;   $sem = thread::semaphore->new(1); #turn off buffering $|++;  sub wait_for_sem {    print threads -> self -> tid. ": waiting semaphore\n";     $sem -> down();     print threads -> self -> tid. ": got semaphore\n";     sleep rand 3;    print threads -> self -> tid. ": releasing semaphore\n";     $sem -> up;   }  threads -> create ( \&wait_for_sem ) 1..100;  foreach $thr ( threads -> list ) {     print "waiting ".$thr->tid." join\n";     $thr -> join;    print "joined ".$thr->tid."\n";  } 

i think buffering what's going wrong code - try $|++.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -