kef has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellow monks,

my guess is, that this is a rather simple questions for those amongst us, who ever used threads and threads::shared before.

I have an array which holds servernames which should be portscanned by multiple threads. My thought was that each thread could theoretically pop a line off the array and scan that host and print the result.

Unfortunately I can't figure out how to start, as I never had worked with threads before and all my attempts failed so far, giving me nothing but errors.
  • Comment on Multiple threads working on a single array

Replies are listed 'Best First'.
Re: Multiple threads working on a single array
by zentara (Cardinal) on Aug 11, 2008 at 13:27 UTC
    as I never had worked with threads before

    Well Reusable threads demo shows a pool of threads working on an array. Your problem will be to keep your network objects contained in the threads (threadsafe), and to clear out the previous run's data, before starting on the next server. Much depends on what modules you will be using in your threads for the portscanning, and whether it is threadsafe.

    You may be better off using forks instead of threads. With a fork, you will be able to handle timeouts easier, and memory cleanup is better. Since you just want results printed out, you can have each forked child print to a file. The only way threads would be useful, is if you need communication between threads in realtime, like thread3 is checking if thread4 is working ok. If you don't need that realtime interaction, forks are better. See Parallel::ForkManager.


    I'm not really a human, but I play one on earth Remember How Lucky You Are
Re: Multiple threads working on a single array
by Anonymous Monk on Aug 11, 2008 at 10:40 UTC
Re: Multiple threads working on a single array
by weismat (Friar) on Aug 11, 2008 at 16:07 UTC
    I think it is a lot easier for you to use Thread::Queue.http://search.cpan.org/~jdhedden/Thread-Queue-2.11/lib/Thread/Queue.pm If you want to understand, what you need to do for a shared array access, then look at the implementation of the module - it is very clear and clean and shows you that locking on arrays is more complex than you might expect.
Re: Multiple threads working on a single array
by Anonymous Monk on Aug 11, 2008 at 10:30 UTC