Advertisement

02.14.2008 at 09:42AM PST, ID: 23163713
[x]
Attachment Details

Problem with thread::shared hash values

Asked by malklavious in Perl Programming Language

Tags:

I'm having some issues using thread and thread::shared to utilize a shared hash in the threads.  The idea is to have a shared memory cache in the form of a hash that has been shared.  However, it does not seem to be getting populated correctly.  Even after populating a value into the cache and sharing it, it does not persist for the next thread.  See the code snippet for a simplified version of what I'm trying to do.

I've even tried to share the individual values in the shared cache (ie: share($shared_cache{$var}) ) but that has not helped.Start Free Trial
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
#!/usr/bin/perl
 
use threads;
use threads::shared;
 
my %shared_cache;
share(%shared_cache);
 
for (my $i; $i < 10; $i++)
{
   my $result = threads->create(\&thread_function, $i);
}
 
sub thread_function($)
{
   my $var = shift;
   if ($shared_cache{$var})
   {
      print "found cached value\n";
   }
   else
   {
      print "no cached value, calculating and caching\n";
      $shared_cache{$var} = calculate_result($var);
   }
 
   return $shared_cache{$var};
}
 
Loading Advertisement...
 
[+][-]02.14.2008 at 09:44AM PST, ID: 20895405

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 7-day free trial to view this Author Comment or ask the Experts your question.

 
[+][-]02.14.2008 at 10:01AM PST, ID: 20895558

At Experts Exchange, members can ask their questions to thousands of technology professionals, also known as Experts. Experts compete and collaborate to answer those questions by leaving comments like this one.

Start your 7-day free trial to view this Expert Comment or ask the Experts your question.

 
[+][-]02.14.2008 at 10:10AM PST, ID: 20895643

View this solution now by starting your 7-day free trial. Setting up your free trial is quick, easy, and secure. We will return you to this solution, unlocked, when you're done.

 

About this solution

Zone: Perl Programming Language
Tags: thread shared hash
Sign Up Now!
Solution Provided By: Adam314
Participating Experts: 2
Solution Grade: A
 
 
[+][-]02.14.2008 at 10:47AM PST, ID: 20895973

Often, when Experts are collaborating with members who have asked questions, they will request additional information about the problem. Askers respond with an author comment like this one.

Start your 7-day free trial to view this Author Comment or ask the Experts your question.

 
 
Loading Advertisement...
20080716-EE-VQP-32 / EE_QW_2_20070628