in reply to Fun with threads

  1. You told the thread to stop only after it stopped, which can never be satisfied.
    use threads; $| ++; threads->create(\&a); while (1) {} sub a { eval(threads->self->join);#Waiting for Godot print "before return\n";#will not show up }
    Here is one normal way to use join:
    use threads; $| ++; $child = threads->create(\&a); $child->join; # I am wating the $child thread to finish first print "Main thread stop\n"; sub a { for (1..5) { print "child is still counting, $_\n"; sleep(3); } print "child thread stop\n"; }
  2. Join provides a kind of coarse method to synchronize, just like what waitpid provided for processes. One process or thread stalled until the others caught up and finished. For finer methods of synchronization, please consider lock, condition, and semaphore. Let's use fork and waitpid to do something similar as what we did in point 1:

    This works:
    $| ++; if (($chld = fork()) == 0) { sleep(3); print "child exit\n"; } else { waitpid $chld, 0; print "parent exit\n"; }
    This hangs:
    $| ++; waitpid $$, 0; #wait for Godot print "exit\n";
  3. In real life, you always need to put an up limit on the number of threads you can have. Where is the limitation? it really depends on your context, your every bit of effort tuning your multi-threaded applications will be appreciated.
In a multi-threading program, always turn on $| for debuging, so you are not confused.

Replies are listed 'Best First'.
Re: Re: Fun with threads
by znu (Acolyte) on Dec 20, 2002 at 02:39 UTC
    Hmmm, i see. So do you mean that since it does print "before return" the join seems to have no effect? Does the thread then stop when it reaches the end of the sub?? Also, what does $| ++; do? thanks!
Re: Re: Fun with threads
by submersible_toaster (Chaplain) on Dec 20, 2002 at 06:44 UTC
    ++pg PMSL @ script that is 'Waiting for Godot'.