in reply to Re^2: Threads sharing a Cache::MemoryCache object??
in thread Threads sharing a Cache::MemoryCache object??
It is often not wise to share an object unless the class itself has been written to support sharing. For example, an object's destructor may get called multiple times, once for each thread's scope exit.
#!/usr/bin/perl use strict; # so useful use threads; use threads::shared; use Cache::SharedMemoryCache; my $lockCache:shared; #marks critical section my $cache = new Cache::SharedMemoryCache(); sub checkCache ($) { my $key = shift; my $val; { lock $lockCache; $val = $cache->get( $key ); print "checking $key = ($val)\n"; } return $val; } sub setCache ($$) { my($key, $newval) = @_; { print "\tsetting $key=$newval\n"; lock $lockCache; $cache->set( $key, $newval, "1 minutes" ); } } # sanity check - test entry from parent thread $|=1; my $testval = int 1 + rand(1234567); print "TESTing: set($testval)... "; setCache("test", "$testval") or die "set failed"; my $testvalget = checkCache("test") or die "get failed\n"; die "got ill. response ($testvalget) from cache" unless $testvalget eq + $testval; print "TESTing finished OK\n"; # to tell when all threads are complete # keep from blocking in a join, so we can accept signals my $threadTerm :shared =0; my $thr1 = threads->new(\&t,1); my $thr2 = threads->new(\&t,10); my $thr3 = threads->new(\&t,20); sub t { my $id = shift; my $sanitycheck = checkCache("test"); print "====== Starting T$id: 'test' is ($sanitycheck) ====\n"; die "seems, that we cannot share the cache right now..." unless $s +anitycheck; sleep (int rand(3)); foreach my $i (1...10) { print "T$id-$i:\t"; my $key = $i + int (rand 3); my $val = checkCache($key); if (! defined $val ) { $val = $id+rand(10); setCache ($key, $val); } sleep (int rand (3)); } $threadTerm++; } # to allow future signals to be recognized while ($threadTerm <3) { sleep 2; } $thr1->join; $thr2->join; $thr3->join; print "C'est ca...\n";
|
|---|