Hi, is it possible to pass a reference to a subroutine to a thread? What I want to do is to give a worker thread a list of subroutines that it should call but this fails. I did not find a kind of 'shared' attribute for subroutines like it is present for scalar/array/hash references. Here is some code that illustrates my problem:
use strict; use warnings; use threads; use threads::shared; use Thread::Queue; my $queue = new Thread::Queue; sub hello { print "Hello\n"; } sub worker { my $tid = threads->self->tid; print "[$tid] Starting\n"; while (my $job = $queue->dequeue) { print "Got a job\n"; } print "[$tid] Terminating\n"; } my @tlist; my $workers = 4; # Start Workers for (my $i = 0; $i < $workers; $i++) { push(@tlist, threads->new(\&worker)); } for (my $i = 0; $i < 10; $i++) { $queue->enqueue(\&hello); # This causes my trouble } sleep(5); # Wait for workers to finish foreach my $w (@tlist) { $queue->enqueue(undef); } foreach my $w (@tlist) { $w->join; }
Does anybody now how I can call the subs that I pass to a thread? Thanks for your help! Kind regards, Stephan

In reply to Threaded Perl: References to subroutines to threads by stephan_a

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.