in reply to Ending up with duplicate keys in a hash?\
Hello coffeemaster1, and welcome to the Monastery!
You can see there are multiple duplicate keys here and I wasn't sure if this was just Data::Dumper printing things out weird as this is a shared variable, or it was actually like this. Is this possible in Perl?
No, absolutely not! It’s a sign that something in your code is seriously broken. :-(
I assumed that if it were to happen the "second" key/value pair would overwrite the first.
Yes, that’s exactly what does happen:
15:57 >perl -MData::Dumper -wE "my %h = (a => 7, b => 13); $h{b} = 42; + print Dumper(\%h);" $VAR1 = { 'b' => 42, 'a' => 7 }; 15:57 >
Could this be caused by the use of a shared variable that is being update in one thread and read in another? (I am using locks when reading and writing to the variable).
You are aware that the Perl lock command is advisory only? In your code you lock(%queue_changes);, but you don’t show any corresponding calls to cond_wait, cond_timedwait, cond_signal, or cond_broadcast to make use of the lock. (See threads::shared.)
You should provide a short, self-contained script which exhibits the anomalous behaviour you’re observing. This will help the monks to help you. But it’s likely that the exercise of producing this script will itself enlighten you as to what’s going wrong in your code.
BTW, this line is wrong:
$queue_changes{$event_id} = %type;
as it puts %type into scalar context and thereby assigns to $queue_changes{$event_id} a fraction such as 6/8.1 I assume you meant:
$queue_changes{$event_id} = \%type;
Another point: this code:
$event_id = int(rand(25000));
is not guaranteed to produce unique event IDs. For that, you would need to keep track of all the IDs already allocated and re-calculate whenever a new ID duplicates an existing one.
1The fraction denotes the number of buckets used in the hash divided by the number of buckets allocated.
Hope that helps,
| Athanasius <°(((>< contra mundum | Iustus alius egestas vitae, eros Piratica, |
|
|---|