Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl threads and hash keys

If a have a hash shared between 2 threads and if I ensure that thread1 just interacts with key1 and thread2 just with key2, can I assume it as thread-safe? If so, do I need to create key1 and key2 before share the hash over the treads or can each thread create its own key? Is there any place where I can get some information about Perl hashes internal mechanisms and its behavior with threads?

like image 613
cirne100 Avatar asked Nov 21 '25 00:11

cirne100


1 Answers

A hash is an array of linked lists. A hashing function converts the key into a number which is used as the index of the array element ("bucket") into which to store the value. More than one key can hash to the same index ("collision"), so the linked lists handle this case.

If a thread modifies one of the linked lists (e.g. to add an element) while another is navigating it (e.g. to fetch an element), It could lead to problems.

As such, adding elements is not safe. You could address this by precreating the elements of the hash (or array).

So that leaves the question of whether accessing existing elements is safe or not. It might be, but there is no guarantee of that.

You might find these interesting:

  • illguts goes into internal details of Perl data structures.
  • Devel::Peek is a very useful tool.
like image 121
ikegami Avatar answered Nov 22 '25 14:11

ikegami