Hi All,

I want to create few threads and want to share objects of class between
threads. Although there is a package Thread::Queue but it only allows
sharing of scalar data.

I tried sending data as a reference parameter to thread but seems like it is
passed as value to thread function. Here is an example where I am passing
reference to scalar variable to the thread function.

*$ cat ref.pl *
#!/usr/bin/perl

use threads;

sub func1()
{
    my $i = shift;
    print "In thread value: $$i\n";
    $$i = 100;
    print "In thread value: $$i\n";
}

sub func2()
{
    my $i = shift;
    print "func2: i: $$i\n";
    $$i = 30;
}

sub func3()
{
    my $i = shift;
    $$i = 10;
    &func2($i);
}

my $i = 0;
&func3(\$i);
print "i = $i\n";
my $thr = threads->create(\&func1, \$i);
$thr->join();
print "i = $i\n";

*$ perl ref.pl *
func2: i: 10
i = 30
In thread value: 30
In thread value: 100
i = 30

As you can see even though $i is passed as reference to thread function, but
value changed in thread function is not getting reflected in main thread.

I know for scalar i can use Thread::Queue package, but I want to exchange
objects of a class. I tried this example just to validate the concept.

Is there any way I can share objects across threads? These objects are not
global.

Thanks and Regards,
Prasad

Reply via email to