Here is another way to slow things down for visualization. Add a delay in the thread sub.
sub thread { my $val = shift; foreach my $x (1..10) { print "hello $x from thread $val\n"; my $delay = int rand 5; sleep $delay; } }
it seems that perl's idea of multithreading is just as good as calling the avarage subroutine :/

On a single cpu machine, that is true.

In real world work, threading is more useful as a means of easily sharing variables between different code blocks running independently, using threads::shared. Otherwise, forking is usually a better parallel processing solution because of issues like memory reclamation, independence of IO, sharing objects, and a few others gotchas which threads occaisionally cause. For example, look how easy it is for the main thread and the child thread can share the array:

#!/usr/bin/perl use warnings; use threads; use threads::shared; use strict; $|=1; #turn off buffering my @hosts_shared : shared; #declare as shared before setting value @hosts_shared = (1,2,3,4,5); print "@hosts_shared\n"; my $thread = threads->new(sub { print "Run the thread! array should be modified\n"; #modify shared array push @hosts_shared, 42; })->detach(); sleep 1; # cheap hack to allow thread time to work print "@hosts_shared\n"; print "Hit enter to exit\n"; <>;

I'm not really a human, but I play one on earth.
Old Perl Programmer Haiku ................... flash japh

In reply to Re^3: multithreading sample needed by zentara
in thread multithreading sample needed by sweepy838

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.