Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety of global variables in perl

I have following questions:

  1. How is global code executed and global variables initialized in perl?
  2. If I write use package_name; in multiple packages, does the global code execute each time?
  3. Are global variables defined this way thread safe?
like image 683
prashanthkvs Avatar asked Dec 12 '25 09:12

prashanthkvs


1 Answers

Perl makes a complete copy of all code and variables for each thread. Communication between threads is via specially marked shared variables (which in fact are not shared - there is still a copy in each thread, but all the copies get updated). This is a significantly different threading model than many other languages have, so the thread-safety concerns are different - mostly centering around what happens when objects are copied to make a new thread and those objects have some form of resource to something outside the program (e.g. a database connection).

Your question about use isn't really related to threads, as far as I can tell? use does several things; one is loading the specified module and running any top-level code in it; this happens only once per module, not once per use statement.

like image 125
ysth Avatar answered Dec 14 '25 09:12

ysth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!