{
    "mode": "perldoc",
    "parameter": "threads::shared",
    "section": "",
    "url": "https://www.chedong.com/phpMan.php/perldoc/threads%3A%3Ashared/json",
    "generated": "2026-05-30T06:07:18Z",
    "synopsis": "use threads;\nuse threads::shared;\nmy $var :shared;\nmy %hsh :shared;\nmy @ary :shared;\nmy ($scalar, @array, %hash);\nshare($scalar);\nshare(@array);\nshare(%hash);\n$var = $scalarvalue;\n$var = $sharedrefvalue;\n$var = sharedclone($nonsharedrefvalue);\n$var = sharedclone({'foo' => [qw/foo bar baz/]});\n$hsh{'foo'} = $scalarvalue;\n$hsh{'bar'} = $sharedrefvalue;\n$hsh{'baz'} = sharedclone($nonsharedrefvalue);\n$hsh{'quz'} = sharedclone([1..3]);\n$ary[0] = $scalarvalue;\n$ary[1] = $sharedrefvalue;\n$ary[2] = sharedclone($nonsharedrefvalue);\n$ary[3] = sharedclone([ {}, [] ]);\n{ lock(%hash); ...  }\ncondwait($scalar);\ncondtimedwait($scalar, time() + 30);\ncondbroadcast(@array);\ncondsignal(%hash);\nmy $lockvar :shared;\n# condition var != lock var\ncondwait($var, $lockvar);\ncondtimedwait($var, time()+30, $lockvar);",
    "sections": {
        "NAME": {
            "content": "threads::shared - Perl extension for sharing data structures between\nthreads\n",
            "subsections": []
        },
        "VERSION": {
            "content": "This document describes threads::shared version 1.62\n",
            "subsections": []
        },
        "SYNOPSIS": {
            "content": "use threads;\nuse threads::shared;\n\nmy $var :shared;\nmy %hsh :shared;\nmy @ary :shared;\n\nmy ($scalar, @array, %hash);\nshare($scalar);\nshare(@array);\nshare(%hash);\n\n$var = $scalarvalue;\n$var = $sharedrefvalue;\n$var = sharedclone($nonsharedrefvalue);\n$var = sharedclone({'foo' => [qw/foo bar baz/]});\n\n$hsh{'foo'} = $scalarvalue;\n$hsh{'bar'} = $sharedrefvalue;\n$hsh{'baz'} = sharedclone($nonsharedrefvalue);\n$hsh{'quz'} = sharedclone([1..3]);\n\n$ary[0] = $scalarvalue;\n$ary[1] = $sharedrefvalue;\n$ary[2] = sharedclone($nonsharedrefvalue);\n$ary[3] = sharedclone([ {}, [] ]);\n\n{ lock(%hash); ...  }\n\ncondwait($scalar);\ncondtimedwait($scalar, time() + 30);\ncondbroadcast(@array);\ncondsignal(%hash);\n\nmy $lockvar :shared;\n# condition var != lock var\ncondwait($var, $lockvar);\ncondtimedwait($var, time()+30, $lockvar);\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "By default, variables are private to each thread, and each newly created\nthread gets a private copy of each existing variable. This module allows\nyou to share variables across different threads (and pseudo-forks on\nWin32). It is used together with the threads module.\n\nThis module supports the sharing of the following data types only:\nscalars and scalar refs, arrays and array refs, and hashes and hash\nrefs.\n",
            "subsections": []
        },
        "EXPORT": {
            "content": "The following functions are exported by this module: \"share\",\n\"sharedclone\", \"isshared\", \"condwait\", \"condtimedwait\",\n\"condsignal\" and \"condbroadcast\"\n\nNote that if this module is imported when threads has not yet been\nloaded, then these functions all become no-ops. This makes it possible\nto write modules that will work in both threaded and non-threaded\nenvironments.\n",
            "subsections": []
        },
        "FUNCTIONS": {
            "content": "share VARIABLE\n\"share\" takes a variable and marks it as shared:\n\nmy ($scalar, @array, %hash);\nshare($scalar);\nshare(@array);\nshare(%hash);\n\n\"share\" will return the shared rvalue, but always as a reference.\n\nVariables can also be marked as shared at compile time by using the\n\":shared\" attribute:\n\nmy ($var, %hash, @array) :shared;\n\nShared variables can only store scalars, refs of shared variables,\nor refs of shared data (discussed in next section):\n\nmy ($var, %hash, @array) :shared;\nmy $bork;\n\n# Storing scalars\n$var = 1;\n$hash{'foo'} = 'bar';\n$array[0] = 1.5;\n\n# Storing shared refs\n$var = \\%hash;\n$hash{'ary'} = \\@array;\n$array[1] = \\$var;\n\n# The following are errors:\n#   $var = \\$bork;                    # ref of non-shared variable\n#   $hash{'bork'} = [];               # non-shared array ref\n#   push(@array, { 'x' => 1 });       # non-shared hash ref\n\nsharedclone REF\n\"sharedclone\" takes a reference, and returns a shared version of\nits argument, performing a deep copy on any non-shared elements. Any\nshared elements in the argument are used as is (i.e., they are not\ncloned).\n\nmy $cpy = sharedclone({'foo' => [qw/foo bar baz/]});\n\nObject status (i.e., the class an object is blessed into) is also\ncloned.\n\nmy $obj = {'foo' => [qw/foo bar baz/]};\nbless($obj, 'Foo');\nmy $cpy = sharedclone($obj);\nprint(ref($cpy), \"\\n\");         # Outputs 'Foo'\n\nFor cloning empty array or hash refs, the following may also be\nused:\n\n$var = &share([]);   # Same as $var = sharedclone([]);\n$var = &share({});   # Same as $var = sharedclone({});\n\nNot all Perl data types can be cloned (e.g., globs, code refs). By\ndefault, \"sharedclone\" will croak if it encounters such items. To\nchange this behaviour to a warning, then set the following:\n\n$threads::shared::clonewarn = 1;\n\nIn this case, \"undef\" will be substituted for the item to be cloned.\nIf set to zero:\n\n$threads::shared::clonewarn = 0;\n\nthen the \"undef\" substitution will be performed silently.\n\nisshared VARIABLE\n\"isshared\" checks if the specified variable is shared or not. If\nshared, returns the variable's internal ID (similar to \"refaddr()\"\n(see Scalar::Util). Otherwise, returns \"undef\".\n\nif (isshared($var)) {\nprint(\"\\$var is shared\\n\");\n} else {\nprint(\"\\$var is not shared\\n\");\n}\n\nWhen used on an element of an array or hash, \"isshared\" checks if\nthe specified element belongs to a shared array or hash. (It does\nnot check the contents of that element.)\n\nmy %hash :shared;\nif (isshared(%hash)) {\nprint(\"\\%hash is shared\\n\");\n}\n\n$hash{'elem'} = 1;\nif (isshared($hash{'elem'})) {\nprint(\"\\$hash{'elem'} is in a shared hash\\n\");\n}\n\nlock VARIABLE\n\"lock\" places a advisory lock on a variable until the lock goes out\nof scope. If the variable is locked by another thread, the \"lock\"\ncall will block until it's available. Multiple calls to \"lock\" by\nthe same thread from within dynamically nested scopes are safe --\nthe variable will remain locked until the outermost lock on the\nvariable goes out of scope.\n\n\"lock\" follows references exactly *one* level:\n\nmy %hash :shared;\nmy $ref = \\%hash;\nlock($ref);           # This is equivalent to lock(%hash)\n\nNote that you cannot explicitly unlock a variable; you can only wait\nfor the lock to go out of scope. This is most easily accomplished by\nlocking the variable inside a block.\n\nmy $var :shared;\n{\nlock($var);\n# $var is locked from here to the end of the block\n...\n}\n# $var is now unlocked\n\nAs locks are advisory, they do not prevent data access or\nmodification by another thread that does not itself attempt to\nobtain a lock on the variable.\n\nYou cannot lock the individual elements of a container variable:\n\nmy %hash :shared;\n$hash{'foo'} = 'bar';\n#lock($hash{'foo'});          # Error\nlock(%hash);                  # Works\n\nIf you need more fine-grained control over shared variable access,\nsee Thread::Semaphore.\n\ncondwait VARIABLE\ncondwait CONDVAR, LOCKVAR\nThe \"condwait\" function takes a locked variable as a parameter,\nunlocks the variable, and blocks until another thread does a\n\"condsignal\" or \"condbroadcast\" for that same locked variable. The\nvariable that \"condwait\" blocked on is re-locked after the\n\"condwait\" is satisfied. If there are multiple threads\n\"condwait\"ing on the same variable, all but one will re-block\nwaiting to reacquire the lock on the variable. (So if you're only\nusing \"condwait\" for synchronization, give up the lock as soon as\npossible). The two actions of unlocking the variable and entering\nthe blocked wait state are atomic, the two actions of exiting from\nthe blocked wait state and re-locking the variable are not.\n\nIn its second form, \"condwait\" takes a shared, unlocked variable\nfollowed by a shared, locked variable. The second variable is\nunlocked and thread execution suspended until another thread signals\nthe first variable.\n\nIt is important to note that the variable can be notified even if no\nthread \"condsignal\" or \"condbroadcast\" on the variable. It is\ntherefore important to check the value of the variable and go back\nto waiting if the requirement is not fulfilled. For example, to\npause until a shared counter drops to zero:\n\n{ lock($counter); condwait($counter) until $counter == 0; }\n\ncondtimedwait VARIABLE, ABSTIMEOUT\ncondtimedwait CONDVAR, ABSTIMEOUT, LOCKVAR\nIn its two-argument form, \"condtimedwait\" takes a locked variable\nand an absolute timeout in *epoch* seconds (see time() in perlfunc\nfor more) as parameters, unlocks the variable, and blocks until the\ntimeout is reached or another thread signals the variable. A false\nvalue is returned if the timeout is reached, and a true value\notherwise. In either case, the variable is re-locked upon return.\n\nLike \"condwait\", this function may take a shared, locked variable\nas an additional parameter; in this case the first parameter is an\nunlocked condition variable protected by a distinct lock variable.\n\nAgain like \"condwait\", waking up and reacquiring the lock are not\natomic, and you should always check your desired condition after\nthis function returns. Since the timeout is an absolute value,\nhowever, it does not have to be recalculated with each pass:\n\nlock($var);\nmy $abs = time() + 15;\nuntil ($ok = desiredcondition($var)) {\nlast if !condtimedwait($var, $abs);\n}\n# we got it if $ok, otherwise we timed out!\n\ncondsignal VARIABLE\nThe \"condsignal\" function takes a locked variable as a parameter\nand unblocks one thread that's \"condwait\"ing on that variable. If\nmore than one thread is blocked in a \"condwait\" on that variable,\nonly one (and which one is indeterminate) will be unblocked.\n\nIf there are no threads blocked in a \"condwait\" on the variable,\nthe signal is discarded. By always locking before signaling, you can\n(with care), avoid signaling before another thread has entered\ncondwait().\n\n\"condsignal\" will normally generate a warning if you attempt to use\nit on an unlocked variable. On the rare occasions where doing this\nmay be sensible, you can suppress the warning with:\n\n{ no warnings 'threads'; condsignal($foo); }\n\ncondbroadcast VARIABLE\nThe \"condbroadcast\" function works similarly to \"condsignal\".\n\"condbroadcast\", though, will unblock all the threads that are\nblocked in a \"condwait\" on the locked variable, rather than only\none.\n",
            "subsections": []
        },
        "OBJECTS": {
            "content": "threads::shared exports a version of bless() that works on shared\nobjects such that *blessings* propagate across threads.\n\n# Create a shared 'Foo' object\nmy $foo :shared = sharedclone({});\nbless($foo, 'Foo');\n\n# Create a shared 'Bar' object\nmy $bar :shared = sharedclone({});\nbless($bar, 'Bar');\n\n# Put 'bar' inside 'foo'\n$foo->{'bar'} = $bar;\n\n# Rebless the objects via a thread\nthreads->create(sub {\n# Rebless the outer object\nbless($foo, 'Yin');\n\n# Cannot directly rebless the inner object\n#bless($foo->{'bar'}, 'Yang');\n\n# Retrieve and rebless the inner object\nmy $obj = $foo->{'bar'};\nbless($obj, 'Yang');\n$foo->{'bar'} = $obj;\n\n})->join();\n\nprint(ref($foo),          \"\\n\");    # Prints 'Yin'\nprint(ref($foo->{'bar'}), \"\\n\");    # Prints 'Yang'\nprint(ref($bar),          \"\\n\");    # Also prints 'Yang'\n",
            "subsections": []
        },
        "NOTES": {
            "content": "threads::shared is designed to disable itself silently if threads are\nnot available. This allows you to write modules and packages that can be\nused in both threaded and non-threaded applications.\n\nIf you want access to threads, you must \"use threads\" before you \"use\nthreads::shared\". threads will emit a warning if you use it after\nthreads::shared.\n",
            "subsections": []
        },
        "WARNINGS": {
            "content": "condbroadcast() called on unlocked variable\ncondsignal() called on unlocked variable\nSee \"condsignal VARIABLE\", above.\n",
            "subsections": []
        },
        "BUGS AND LIMITATIONS": {
            "content": "When \"share\" is used on arrays, hashes, array refs or hash refs, any\ndata they contain will be lost.\n\nmy @arr = qw(foo bar baz);\nshare(@arr);\n# @arr is now empty (i.e., == ());\n\n# Create a 'foo' object\nmy $foo = { 'data' => 99 };\nbless($foo, 'foo');\n\n# Share the object\nshare($foo);        # Contents are now wiped out\nprint(\"ERROR: \\$foo is empty\\n\")\nif (! exists($foo->{'data'}));\n\nTherefore, populate such variables after declaring them as shared.\n(Scalar and scalar refs are not affected by this problem.)\n\nBlessing a shared item after it has been nested in another shared item\ndoes not propagate the blessing to the shared reference:\n\nmy $foo = &share({});\nmy $bar = &share({});\n$bar->{foo} = $foo;\nbless($foo, 'baz');   # $foo is now of class 'baz',\n# but $bar->{foo} is unblessed.\n\nTherefore, you should bless objects before sharing them.\n\nIt is often not wise to share an object unless the class itself has been\nwritten to support sharing. For example, a shared object's destructor\nmay get called multiple times, once for each thread's scope exit, or may\nnot get called at all if it is embedded inside another shared object.\nAnother issue is that the contents of hash-based objects will be lost\ndue to the above mentioned limitation. See examples/class.pl (in the\nCPAN distribution of this module) for how to create a class that\nsupports object sharing.\n\nDestructors may not be called on objects if those objects still exist at\nglobal destruction time. If the destructors must be called, make sure\nthere are no circular references and that nothing is referencing the\nobjects before the program ends.\n\nDoes not support \"splice\" on arrays. Does not support explicitly\nchanging array lengths via $#array -- use \"push\" and \"pop\" instead.\n\nTaking references to the elements of shared arrays and hashes does not\nautovivify the elements, and neither does slicing a shared array/hash\nover non-existent indices/keys autovivify the elements.\n\n\"share()\" allows you to \"share($hashref->{key})\" and\n\"share($arrayref->[idx])\" without giving any error message. But the\n\"$hashref->{key}\" or \"$arrayref->[idx]\" is not shared, causing the error\n\"lock can only be used on shared values\" to occur when you attempt to\n\"lock($hashref->{key})\" or \"lock($arrayref->[idx])\" in another thread.\n\nUsing \"refaddr()\" is unreliable for testing whether or not two shared\nreferences are equivalent (e.g., when testing for circular references).\nUse isshared(), instead:\n\nuse threads;\nuse threads::shared;\nuse Scalar::Util qw(refaddr);\n\n# If ref is shared, use threads::shared's internal ID.\n# Otherwise, use refaddr().\nmy $addr1 = isshared($ref1) || refaddr($ref1);\nmy $addr2 = isshared($ref2) || refaddr($ref2);\n\nif ($addr1 == $addr2) {\n# The refs are equivalent\n}\n\neach() does not work properly on shared references embedded in shared\nstructures. For example:\n\nmy %foo :shared;\n$foo{'bar'} = sharedclone({'a'=>'x', 'b'=>'y', 'c'=>'z'});\n\nwhile (my ($key, $val) = each(%{$foo{'bar'}})) {\n...\n}\n\nEither of the following will work instead:\n\nmy $ref = $foo{'bar'};\nwhile (my ($key, $val) = each(%{$ref})) {\n...\n}\n\nforeach my $key (keys(%{$foo{'bar'}})) {\nmy $val = $foo{'bar'}{$key};\n...\n}\n\nThis module supports dual-valued variables created using \"dualvar()\"\nfrom Scalar::Util. However, while $! acts like a dualvar, it is\nimplemented as a tied SV. To propagate its value, use the follow\nconstruct, if needed:\n\nmy $errno :shared = dualvar($!,$!);\n\nView existing bug reports at, and submit any new bugs, problems,\npatches, etc. to:\n<http://rt.cpan.org/Public/Dist/Display.html?Name=threads-shared>\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "threads::shared on MetaCPAN:\n<https://metacpan.org/release/threads-shared>\n\nCode repository for CPAN distribution:\n<https://github.com/Dual-Life/threads-shared>\n\nthreads, perlthrtut\n\n<http://www.perl.com/pub/a/2002/06/11/threads.html> and\n<http://www.perl.com/pub/a/2002/09/04/threads.html>\n\nPerl threads mailing list: <http://lists.perl.org/list/ithreads.html>\n\nSample code in the *examples* directory of this distribution on CPAN.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Artur Bergman <sky AT crucially DOT net>\n\nDocumentation borrowed from the old Thread.pm.\n\nCPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>.\n",
            "subsections": []
        },
        "LICENSE": {
            "content": "threads::shared is released under the same license as Perl.\n",
            "subsections": []
        }
    },
    "summary": "threads::shared - Perl extension for sharing data structures between threads",
    "flags": [],
    "examples": [],
    "see_also": []
}