thread problem

D

Dave Saville

I am having a problem with threads on a Raspberry Pi. (Note - have
never used threads in perl. Only C)

use strict;
use warnings;
use threads;
use threads::shared;
my $foo = 'foo';
threads->create({'void' => 1}, 'try');
sleep 2;
print "$foo - done\n";
sleep 5;
sub try
{
threads->detach();
$foo = 'bar';
sleep 5;
return;
}

Why isn't $foo changing in the main thread? I have tried passing $foo
as an argument to try both as itself and as a scalar ref. No way can I
get $foo to change value in main.

What I am trying to do is use a thread to essentially tail a pipe and
raise a flag in main if it sees a certain string appear.The main
thread can't tail it because I don't want to block. So my "real* sub
is:

sub get_title
{
threads->detach();
my $ref = shift;
open my $FIFO, '<', '/home/pi/fifo_stdout' or die "Can't open
fifo_stdout $!";

while ( <$FIFO> )
{
if ( m{^StreamTitle='([^']*)'} )
{
$$ref = $1;
}
}
}
 
R

Rainer Weikusat

[...]
use strict;
use warnings;
use threads;
use threads::shared;
my $foo = 'foo';
threads->create({'void' => 1}, 'try');
sleep 2;
print "$foo - done\n";
sleep 5;
sub try
{
threads->detach();
$foo = 'bar';
sleep 5;
return;
}

Why isn't $foo changing in the main thread?

Because you didn't declare it as shared variable.

----------
use strict;
use warnings;
use threads;
use threads::shared;
my $foo : shared = 'foo';
threads->create({'void' => 1}, 'try');
sleep 2;
print "$foo - done\n";
sleep 5;
sub try
{
threads->detach();
$foo = 'bar';
sleep 5;
return;
}
---------

[...]
What I am trying to do is use a thread to essentially tail a pipe and
raise a flag in main if it sees a certain string appear.The main
thread can't tail it because I don't want to block.

Using threads in this way, especially perl ithreads, is almost
certainly not a good idea. What's your main thread doing? If it is
'handling other I/O', you should consider using select or a module
providing access to a similar system call. The IO::poll
implementations is beyond braindead. OTOH, IO::EPoll is only 'slightly
bizarre', eg, it uses 3 hashes to map file handles to various things
instead of putting all "per filehandle" attributes into a suitable
object and let the kernel maintain a pointer to that, something which
also works in perl 5 because its automatich memory management system
wasn't built on the wrong assumption that pointer to objects cannot
exist outside of the address space of the process which created them.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top