using of hashes in threadqueues

  • Thread starter Marc Schoechlin
  • Start date
M

Marc Schoechlin

Hi !

I would like to transfer hashes over a threadqueue, but It seems that
this is not possible.

Any hints ?

Any workarounds ?

Look at my testcase:
---
#!/usr/bin/env perl

use warnings;
use strict;
use threads;
use Thread::Queue;
use Data::Dumper;

my $q = new Thread::Queue;

sub ttest(){
while (1){
my %h;
# compute something
$h{tid} = threads->self->tid();$h{time} = time();
print "DEBUG-IN:".Dumper(\%h)."\n";
# enqueue the result
$q->enqueue(\%h);
sleep 1;
}
}

# start two threads
threads->create("ttest");
threads->create("ttest");

# do something with the results of ttest()
while (1){
my %f = $q->dequeue();
print "DEBUG-OUT:".Dumper(\%f)."\n";
print "DEBUG-OUT: time: ".$f{time}." tid:".$f{tid}."\n";
}
 
X

xhoster

Marc Schoechlin said:
Hi !

I would like to transfer hashes over a threadqueue, but It seems that
this is not possible.

Any hints ?

Yeah. Shared variables cannot hold references to unshared variables.
Any workarounds ?

Share the hash before you try to shove it into the queue.
Look at my testcase:
---
#!/usr/bin/env perl

use warnings;
use strict;
use threads;
use Thread::Queue;
use Data::Dumper;

my $q = new Thread::Queue;

sub ttest(){
while (1){
my %h;

my %h : shared;
# compute something
$h{tid} = threads->self->tid();$h{time} = time();
print "DEBUG-IN:".Dumper(\%h)."\n";
# enqueue the result
$q->enqueue(\%h);
sleep 1;
}
}

# start two threads
threads->create("ttest");
threads->create("ttest");

# do something with the results of ttest()
while (1){
my %f = $q->dequeue();

This is unrelated to the question you asked, but that should be:

my %f = %{$q->dequeue()};

(Or probably better, use my $f = $q->dequeue() and the derefence when
needed upon use.)
print "DEBUG-OUT:".Dumper(\%f)."\n";
print "DEBUG-OUT: time: ".$f{time}." tid:".$f{tid}."\n";
}



Xho
 

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

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top