Re: sharing handles between threads

[email protected] ("Wiebren Braakman")
Newsgroups perl.ithreads
Message-ID <[email protected]>
It worked :)

Now i placed the connection in a sepperate module and i tried to make a
lock,

the folowing works:

#!/usr/local/bin/perl
use threads;
use threads::shared;
use strict;
my $lock : shared;
threads->create("test_sub", 0, test->new())->detach();
threads->create("test_sub", 1, test->new())->detach();
sub test_sub {
    my ($num, $test) = @_;
    while(1)
    {
        print "Test $num ".$test->test()."\n";
    }
}
while(1)
{
    sleep 10;
}

package test;
use strict;
use POSIX qw/strftime/;
use threads;
use threads::shared;

#my $lock : shared;

sub new {
    my $class   = shift;
    my $self    = bless { }, $class;
#   ($lock) = @_;
    bless $self;
    return $self;
}

sub test {
    my $self = shift;
    my $result = "Lock : ".strftime("%X", localtime(time));
    lock($lock);
    $result .= " Locked : ".strftime("%X", localtime(time));
    sleep 3;
    return $result." Unlock : ".strftime("%X", localtime(time));
}
1;

when i put the module in a sepperate pm file it does not recocnize the lock
variable and gives the error "Global symbol "$lock" requires explicit
package name at test.pm line 21.". is there al way to share a variable
between modules?

mvg,

Wiebren Braakman

"Steve Schein" <[email protected]> schreef in bericht
news:1085512266.2778.29.camel@Development...
> <snip entire post>
> >
> > Is there a way to share handles between threads? When I try it I get the
> > error
> > "handle 2 is owned by thread 854eee8 (handles can't be shared between
> > threads and your driver may need a CLONE method added)"
> >
> > I need it to be one object handle because I have multiple threads that
all
> > need to use one outgoing socket connection.
>
>
> >>> Wiebren - there a couple of different ways to manage this.  You
> should, however, first figure out where the "CLONE method" error is
> originating.  I've seen that when attempting multi-threaded applications
> with older version of the DBI package.
>
> If all communication will go through a single socket, then you can
> either:
>
> 1) First create the socket handle and as you spawn new threads you can
> pass the handle along (eg. $thr = threads->create(\&subroutine,
> $socket_handle);  # use references to socket handle as desired
>
> 2) Probably the cleanest approach is to have all your threads open up
> sockets (as needed) to connect to the single "outgoing" socket.  This
> way there is no sharing of resources.
>
> I hope this helps!
>
> Steve
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.