Beefy Boxes and Bandwidth Generously Provided by pair Networks DiBona
Welcome to the Monastery
 
PerlMonks  

Re^3: multithreading sample needed

by zentara (Archbishop)
on May 02, 2012 at 10:31 UTC ( #968418=note: print w/ replies, xml ) Need Help??


in reply to Re^2: multithreading sample needed
in thread multithreading sample needed

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


Comment on Re^3: multithreading sample needed
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://968418]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2013-05-22 04:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best material for plates (tableware) is:









    Results (453 votes), past polls