rastoboy has asked for the wisdom of the Perl Monks concerning the following question:
So just when I think I've got this threading thing figured out...;-)
I'm trying to use Thread::Queue to coordinate some simple activities which need to occur simultaneously. Basically I need to run them in a loop until X happens. Basically I'm running a wget, while monitoring cpu and memory usage.
The examples I've seen for how to use this module are all feeding information into a thread, where the thread then acts on them in real time. I just want it to continue doing something until I say stop. The technique I'm using--queueing a single bit of data and using Thread::Queue->peek() in the thread to see if it's true, seems to work fine when I have a single thread. But if I have more than one thread, only the last thread created seems to be able to use peek():
In this case, only the monitor_mem loop gets executed. If I comment out the memory monitoring thread creation and joining, the cpu stuff works fine.#!/usr/bin/perl use strict; use warnings; use threads; use threads::shared; use Thread::Queue; my $q = Thread::Queue->new; my $done : shared; $done = 0; my $wget_thread = threads->create( \&wget_sub ); my $cpu_monitor_thread = threads->create( \&monitor_cpu ); my $mem_monitor_thread = threads->create( \&monitor_mem ); $q->enqueue(1); $wget_thread->join(); $q->dequeue; my $cpu = $cpu_monitor_thread->join(); my $mem = $mem_monitor_thread->join(); print "cpu usage: $cpu\n"; print "mem usage: $mem\n"; sub wget_sub { my $wget = `wget http://10.3.13.4/testfile.dat`; $done = 1; lock($done); print "wget:\n$wget\n"; return 1; } sub monitor_cpu { my $cap; while ( my $val = $q->peek(0) ) { #this does not get evaluated to +true, ever $cap .= `bash cpu.sh; sleep 2`; } return $cap; } sub monitor_mem { my $cap; while ( my $val = $q->peek(0) ) { $cap .= `perl mem.pl; sleep 2`; } return $cap; }
What am I doing wrong? Any input would be greatly appreciated!
peek(0) ) { $cap .= `bash cpu.sh; sleep 2`; } return $cap; } sub monitor_mem { my $cap; while ( my $val = $q-
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: failing with Thread::Queue
by BrowserUk (Patriarch) on Mar 22, 2012 at 20:43 UTC | |
by rastoboy (Monk) on Mar 22, 2012 at 21:08 UTC | |
by BrowserUk (Patriarch) on Mar 22, 2012 at 21:36 UTC | |
by rastoboy (Monk) on Mar 22, 2012 at 22:10 UTC | |
by BrowserUk (Patriarch) on Mar 22, 2012 at 21:22 UTC |