473,507 Members | 2,375 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Howto share filehandles between threads?

I am trying to teach myself perl by writing a program I've been meaning
to implement, so I am pretty green in perl. I'm having problems sharing
filehandles opened by a thread - been RTFM for a few days, but am having
no luck.

I am attempting to write a threaded server program that listens on a
socket for requests, then passes the socket's filehandle to an event
processor routine, while the listener thread keeps on listening.
However, I cannot seem to be able to successfully pass the filehandle
from the listener thread to the event handler.

For testing purposes, I've tried to get the logic down using a thread to
open a filehandle and pass it back to the non-threaded routine as follows:

--------- start ------------
#!/usr/bin/perl

use threads;
use threads::shared;

my $FH : shared;

threads->new(sub {
open($LFH,"< /tmp/junk") || die $!;
$FH=$LFH;
print "[$FH]\n";
#while (<$LFH>) {print "> $_";}
})->join;

print "[$FH]\n";
while (<$FH>) {print "> $_";}

---------- end -------------

Running it gives:
"thread failed to start: Invalid value for shared scalar at ./x.pl line 10."

Any help on how to share a filehandle opened in a thread would be
GREATLY appreciated.

TIA
Jun 2 '06 #1
3 11563
On Fri, 02 Jun 2006 08:23:07 -0500, Sako <ri*******@NOSPAMdls.net>
wrote:
Any help on how to share a filehandle opened in a thread would be
GREATLY appreciated.


Hi, BrowserUk figured it out on perlmonks awhile back, what you
need to do basically is get the fileno of the filehandle, and pass
it around through shared variables.

See:
http://perlmonks.org?node_id=395513
Also of interest may be
http://perlmonks.org?node_id=501725

Here is a little demo I worked up for myself.

#!/usr/bin/perl
use warnings;
use strict;
use threads;
use threads::shared;

my %shash;
#share(%shash); #will work only for first level keys
my %hash;

share ($shash{'go'});
share ($shash{'fileno'});
share ($shash{'pid'});
share ($shash{'die'});

$shash{'go'} = 0;
$shash{'fileno'} = -1;
$shash{'pid'} = -1;
$shash{'die'} = 0;

$hash{'thread'} = threads->new(\&work);

$shash{'go'} = 1;

sleep 1; # cheap hack to allow thread to setup

my $fileno = $shash{'fileno'};
open (my $fh, "<&=$fileno") or warn "$!\n";

while ( <$fh> ){ print "In main-> $_"; }

#wait for keypress to keep main thread alive
<>;

# control-c to exit

################################################## ################
sub work{
$|++;
while(1){
if($shash{'die'} == 1){ return };

if ( $shash{'go'} == 1 ){

my $pid = open(FH, "top -b |" ) or warn "$!\n";
my $fileno = fileno(FH);
print "fileno->$fileno\n";
$shash{'fileno'} = $fileno;

$shash{'go'} = 0; #turn off self before returning
}else
{ sleep 1 }
}
}
################################################## ###################
__END__



--
I'm not really a human, but I play one on earth.
http://zentara.net/japh.html
Jun 3 '06 #2
zentara wrote:
On Fri, 02 Jun 2006 08:23:07 -0500, Sako <ri*******@NOSPAMdls.net>
wrote:

Any help on how to share a filehandle opened in a thread would be
GREATLY appreciated.

Hi, BrowserUk figured it out on perlmonks awhile back, what you
need to do basically is get the fileno of the filehandle, and pass
it around through shared variables.

See:
http://perlmonks.org?node_id=395513
Also of interest may be
http://perlmonks.org?node_id=501725

Here is a little demo I worked up for myself.

#!/usr/bin/perl
use warnings;
use strict;
use threads;
use threads::shared;

my %shash;
#share(%shash); #will work only for first level keys
my %hash;

share ($shash{'go'});
share ($shash{'fileno'});
share ($shash{'pid'});
share ($shash{'die'});

$shash{'go'} = 0;
$shash{'fileno'} = -1;
$shash{'pid'} = -1;
$shash{'die'} = 0;

$hash{'thread'} = threads->new(\&work);

$shash{'go'} = 1;

sleep 1; # cheap hack to allow thread to setup

my $fileno = $shash{'fileno'};
open (my $fh, "<&=$fileno") or warn "$!\n";

while ( <$fh> ){ print "In main-> $_"; }

#wait for keypress to keep main thread alive
<>;

# control-c to exit

################################################## ################
sub work{
$|++;
while(1){
if($shash{'die'} == 1){ return };

if ( $shash{'go'} == 1 ){

my $pid = open(FH, "top -b |" ) or warn "$!\n";
my $fileno = fileno(FH);
print "fileno->$fileno\n";
$shash{'fileno'} = $fileno;

$shash{'go'} = 0; #turn off self before returning
}else
{ sleep 1 }
}
}
################################################## ###################
__END__


Thx much!
Jun 5 '06 #3
Sako <ri*******@NOSPAMdls.net> wrote:
I am trying to teach myself perl by writing a program I've been meaning
to implement, so I am pretty green in perl. I'm having problems sharing
filehandles opened by a thread - been RTFM for a few days, but am having
no luck.
I think Perl is a great language, but not for threading. You should
probably either choose a different task to be your introduction to Perl;
or, if threading is central to what you do, then choose to learn a
different language.

I am attempting to write a threaded server program that listens on a
socket for requests, then passes the socket's filehandle to an event
processor routine, while the listener thread keeps on listening.
However, I cannot seem to be able to successfully pass the filehandle
from the listener thread to the event handler.


If you are going to start a new thread for each session (which I wouldn't
recommend, but then again I don't recommend this whole situation), then I
wouldn't pass the handle at all. Simply stash the handle in a variable
whose scopes spans both the listener and the event handler. A child thread
glombs onto whatever handle was stored in a variable at the time it was
created. This requires the listener to be the "master" thread.

use strict;
use warnings;
use threads;
use threads::shared;
$|=1;
my $conn;
foreach (1..10) {
undef $conn;
open $conn, ">/tmp/foo_$_" or die $!;
threads->create("do_it", $_);
};
$_->join foreach threads->list();
sub do_it {
my $request=shift;
foreach (1..100)
{
print $conn "$request $_\n";
select undef,undef,undef, 0.1;
};
};

Xho

--
-------------------- http://NewsReader.Com/ --------------------
Usenet Newsgroup Service $9.95/Month 30GB
Jun 5 '06 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3825
by: Logan | last post by:
Several people asked me for the following HOWTO, so I decided to post it here (though it is still very 'alpha' and might contain many (?) mistakes; didn't test what I wrote, but wrote it - more or...
1
5808
by: Gernot Hillier | last post by:
-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi! I'm the developer of a Linux ISDN application which uses embedded Python for controlling the communication. It starts several threads (i.e....
2
1980
by: Rudi | last post by:
Is there anyone who can point me to a good tutorial on how to create a multithreaded class library? Class A is a controller that starts up a number of threads of code in Class B. Class B raises...
6
1987
by: Gary Lee | last post by:
In VB.NET using CDO, I'd like to allow multiple threads to share a single MAPI.Session object. If I declare and instantiate sessions within each thread, I'm OK (although this negates the...
0
1472
by: Mark Harrison | last post by:
HOWTO: Integrating Posgresql queries into an event loop. Mark Harrison mh@pixar.com May 27, 2004 Problem ------- The commonly used postgresql APIs will block until completed.
13
1651
by: Yannick | last post by:
Hi, I would like to program a small game in Python, kind of like robocode (http://robocode.sourceforge.net/). Problem is that I would have to share the CPU between all the robots, and thus...
3
5023
by: coltrane | last post by:
Can someone direct me to a reference that describes how to create a context menu for a selected row in a datagrid? I have come across many threads regarding context menus and datagrids but they all...
0
1455
by: norseman | last post by:
Daniel de Sousa Barros wrote: ================================================ Click Start/settings/control panel/system/advanced/settings(in \ performance area)/advanced/change set System...
0
7319
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
7031
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7485
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
5042
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4702
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1542
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
760
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
412
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.