{
    "content": [
        {
            "type": "text",
            "text": "# threads (man)\n\n## NAME\n\nthreads - Perl interpreter-based threads\n\n## SYNOPSIS\n\nuse threads ('yield',\n'stacksize' => 64*4096,\n'exit' => 'threadsonly',\n'stringify');\nsub startthread {\nmy @args = @;\nprint('Thread started: ', join(' ', @args), \"\\n\");\n}\nmy $thr = threads->create('startthread', 'argument');\n$thr->join();\nthreads->create(sub { print(\"I am a thread\\n\"); })->join();\nmy $thr2 = async { foreach (@files) { ... } };\n$thr2->join();\nif (my $err = $thr2->error()) {\nwarn(\"Thread error: $err\\n\");\n}\n# Invoke thread in list context (implicit) so it can return a list\nmy ($thr) = threads->create(sub { return (qw/a b c/); });\n# or specify list context explicitly\nmy $thr = threads->create({'context' => 'list'},\nsub { return (qw/a b c/); });\nmy @results = $thr->join();\n$thr->detach();\n# Get a thread's object\n$thr = threads->self();\n$thr = threads->object($tid);\n# Get a thread's ID\n$tid = threads->tid();\n$tid = $thr->tid();\n$tid = \"$thr\";\n# Give other threads a chance to run\nthreads->yield();\nyield();\n# Lists of non-detached threads\nmy @threads = threads->list();\nmy $threadcount = threads->list();\nmy @running = threads->list(threads::running);\nmy @joinable = threads->list(threads::joinable);\n# Test thread objects\nif ($thr1 == $thr2) {\n...\n}\n# Manage thread stack size\n$stacksize = threads->getstacksize();\n$oldsize = threads->setstacksize(32*4096);\n# Create a thread with a specific context and stack size\nmy $thr = threads->create({ 'context'    => 'list',\n'stacksize' => 32*4096,\n'exit'       => 'threadonly' },\n\\&foo);\n# Get thread's context\nmy $wantarray = $thr->wantarray();\n# Check thread's state\nif ($thr->isrunning()) {\nsleep(1);\n}\nif ($thr->isjoinable()) {\n$thr->join();\n}\n# Send a signal to a thread\n$thr->kill('SIGUSR1');\n# Exit a thread\nthreads->exit();\n\n## DESCRIPTION\n\nSince Perl 5.8, thread programming has been available using a model called interpreter\nthreads which provides a new Perl interpreter for each thread, and, by default, results in no\ndata or state information being shared between threads.\n\n## Sections\n\n- **NAME**\n- **VERSION**\n- **WARNING**\n- **SYNOPSIS**\n- **DESCRIPTION**\n- **EXITING A THREAD** (1 subsections)\n- **THREAD STATE**\n- **THREAD CONTEXT** (4 subsections)\n- **THREAD STACK SIZE**\n- **THREAD SIGNALLING**\n- **WARNINGS**\n- **ERRORS**\n- **BUGS AND LIMITATIONS**\n- **REQUIREMENTS**\n- **SEE ALSO**\n- **AUTHOR**\n- **LICENSE**\n- **ACKNOWLEDGEMENTS**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "threads",
        "section": "",
        "mode": "man",
        "summary": "threads - Perl interpreter-based threads",
        "synopsis": "use threads ('yield',\n'stacksize' => 64*4096,\n'exit' => 'threadsonly',\n'stringify');\nsub startthread {\nmy @args = @;\nprint('Thread started: ', join(' ', @args), \"\\n\");\n}\nmy $thr = threads->create('startthread', 'argument');\n$thr->join();\nthreads->create(sub { print(\"I am a thread\\n\"); })->join();\nmy $thr2 = async { foreach (@files) { ... } };\n$thr2->join();\nif (my $err = $thr2->error()) {\nwarn(\"Thread error: $err\\n\");\n}\n# Invoke thread in list context (implicit) so it can return a list\nmy ($thr) = threads->create(sub { return (qw/a b c/); });\n# or specify list context explicitly\nmy $thr = threads->create({'context' => 'list'},\nsub { return (qw/a b c/); });\nmy @results = $thr->join();\n$thr->detach();\n# Get a thread's object\n$thr = threads->self();\n$thr = threads->object($tid);\n# Get a thread's ID\n$tid = threads->tid();\n$tid = $thr->tid();\n$tid = \"$thr\";\n# Give other threads a chance to run\nthreads->yield();\nyield();\n# Lists of non-detached threads\nmy @threads = threads->list();\nmy $threadcount = threads->list();\nmy @running = threads->list(threads::running);\nmy @joinable = threads->list(threads::joinable);\n# Test thread objects\nif ($thr1 == $thr2) {\n...\n}\n# Manage thread stack size\n$stacksize = threads->getstacksize();\n$oldsize = threads->setstacksize(32*4096);\n# Create a thread with a specific context and stack size\nmy $thr = threads->create({ 'context'    => 'list',\n'stacksize' => 32*4096,\n'exit'       => 'threadonly' },\n\\&foo);\n# Get thread's context\nmy $wantarray = $thr->wantarray();\n# Check thread's state\nif ($thr->isrunning()) {\nsleep(1);\n}\nif ($thr->isjoinable()) {\n$thr->join();\n}\n# Send a signal to a thread\n$thr->kill('SIGUSR1');\n# Exit a thread\nthreads->exit();",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "WARNING",
                "lines": 7,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 81,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 187,
                "subsections": []
            },
            {
                "name": "EXITING A THREAD",
                "lines": 16,
                "subsections": [
                    {
                        "name": "die()",
                        "lines": 38
                    }
                ]
            },
            {
                "name": "THREAD STATE",
                "lines": 17,
                "subsections": []
            },
            {
                "name": "THREAD CONTEXT",
                "lines": 6,
                "subsections": [
                    {
                        "name": "Explicit context",
                        "lines": 27
                    },
                    {
                        "name": "Implicit context",
                        "lines": 12
                    },
                    {
                        "name": "$thr->wantarray()",
                        "lines": 2
                    },
                    {
                        "name": "threads->wantarray()",
                        "lines": 3
                    }
                ]
            },
            {
                "name": "THREAD STACK SIZE",
                "lines": 67,
                "subsections": []
            },
            {
                "name": "THREAD SIGNALLING",
                "lines": 82,
                "subsections": []
            },
            {
                "name": "WARNINGS",
                "lines": 30,
                "subsections": []
            },
            {
                "name": "ERRORS",
                "lines": 22,
                "subsections": []
            },
            {
                "name": "BUGS AND LIMITATIONS",
                "lines": 201,
                "subsections": []
            },
            {
                "name": "REQUIREMENTS",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 15,
                "subsections": []
            },
            {
                "name": "AUTHOR",
                "lines": 4,
                "subsections": []
            },
            {
                "name": "LICENSE",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "ACKNOWLEDGEMENTS",
                "lines": 15,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "threads - Perl interpreter-based threads\n",
                "subsections": []
            },
            "VERSION": {
                "content": "This document describes threads version 2.26\n",
                "subsections": []
            },
            "WARNING": {
                "content": "The \"interpreter-based threads\" provided by Perl are not the fast, lightweight system for\nmultitasking that one might expect or hope for.  Threads are implemented in a way that makes\nthem easy to misuse.  Few people know how to use them correctly or will be able to provide\nhelp.\n\nThe use of interpreter-based threads in perl is officially discouraged.\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "use threads ('yield',\n'stacksize' => 64*4096,\n'exit' => 'threadsonly',\n'stringify');\n\nsub startthread {\nmy @args = @;\nprint('Thread started: ', join(' ', @args), \"\\n\");\n}\nmy $thr = threads->create('startthread', 'argument');\n$thr->join();\n\nthreads->create(sub { print(\"I am a thread\\n\"); })->join();\n\nmy $thr2 = async { foreach (@files) { ... } };\n$thr2->join();\nif (my $err = $thr2->error()) {\nwarn(\"Thread error: $err\\n\");\n}\n\n# Invoke thread in list context (implicit) so it can return a list\nmy ($thr) = threads->create(sub { return (qw/a b c/); });\n# or specify list context explicitly\nmy $thr = threads->create({'context' => 'list'},\nsub { return (qw/a b c/); });\nmy @results = $thr->join();\n\n$thr->detach();\n\n# Get a thread's object\n$thr = threads->self();\n$thr = threads->object($tid);\n\n# Get a thread's ID\n$tid = threads->tid();\n$tid = $thr->tid();\n$tid = \"$thr\";\n\n# Give other threads a chance to run\nthreads->yield();\nyield();\n\n# Lists of non-detached threads\nmy @threads = threads->list();\nmy $threadcount = threads->list();\n\nmy @running = threads->list(threads::running);\nmy @joinable = threads->list(threads::joinable);\n\n# Test thread objects\nif ($thr1 == $thr2) {\n...\n}\n\n# Manage thread stack size\n$stacksize = threads->getstacksize();\n$oldsize = threads->setstacksize(32*4096);\n\n# Create a thread with a specific context and stack size\nmy $thr = threads->create({ 'context'    => 'list',\n'stacksize' => 32*4096,\n'exit'       => 'threadonly' },\n\\&foo);\n\n# Get thread's context\nmy $wantarray = $thr->wantarray();\n\n# Check thread's state\nif ($thr->isrunning()) {\nsleep(1);\n}\nif ($thr->isjoinable()) {\n$thr->join();\n}\n\n# Send a signal to a thread\n$thr->kill('SIGUSR1');\n\n# Exit a thread\nthreads->exit();\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "Since Perl 5.8, thread programming has been available using a model called interpreter\nthreads which provides a new Perl interpreter for each thread, and, by default, results in no\ndata or state information being shared between threads.\n\n(Prior to Perl 5.8, 5005threads was available through the \"Thread.pm\" API.  This threading\nmodel has been deprecated, and was removed as of Perl 5.10.0.)\n\nAs just mentioned, all variables are, by default, thread local.  To use shared variables, you\nneed to also load threads::shared:\n\nuse threads;\nuse threads::shared;\n\nWhen loading threads::shared, you must \"use threads\" before you \"use threads::shared\".\n(\"threads\" will emit a warning if you do it the other way around.)\n\nIt is strongly recommended that you enable threads via \"use threads\" as early as possible in\nyour script.\n\nIf needed, scripts can be written so as to run on both threaded and non-threaded Perls:\n\nmy $canusethreads = eval 'use threads; 1';\nif ($canusethreads) {\n# Do processing using threads\n...\n} else {\n# Do it without using threads\n...\n}\n\n$thr = threads->create(FUNCTION, ARGS)\nThis will create a new thread that will begin execution with the specified entry point\nfunction, and give it the ARGS list as parameters.  It will return the corresponding\nthreads object, or \"undef\" if thread creation failed.\n\nFUNCTION may either be the name of a function, an anonymous subroutine, or a code ref.\n\nmy $thr = threads->create('funcname', ...);\n# or\nmy $thr = threads->create(sub { ... }, ...);\n# or\nmy $thr = threads->create(\\&func, ...);\n\nThe \"->new()\" method is an alias for \"->create()\".\n\n$thr->join()\nThis will wait for the corresponding thread to complete its execution.  When the thread\nfinishes, \"->join()\" will return the return value(s) of the entry point function.\n\nThe context (void, scalar or list) for the return value(s) for \"->join()\" is determined\nat the time of thread creation.\n\n# Create thread in list context (implicit)\nmy ($thr1) = threads->create(sub {\nmy @results = qw(a b c);\nreturn (@results);\n});\n#   or (explicit)\nmy $thr1 = threads->create({'context' => 'list'},\nsub {\nmy @results = qw(a b c);\nreturn (@results);\n});\n# Retrieve list results from thread\nmy @res1 = $thr1->join();\n\n# Create thread in scalar context (implicit)\nmy $thr2 = threads->create(sub {\nmy $result = 42;\nreturn ($result);\n});\n# Retrieve scalar result from thread\nmy $res2 = $thr2->join();\n\n# Create a thread in void context (explicit)\nmy $thr3 = threads->create({'void' => 1},\nsub { print(\"Hello, world\\n\"); });\n# Join the thread in void context (i.e., no return value)\n$thr3->join();\n\nSee \"THREAD CONTEXT\" for more details.\n\nIf the program exits without all threads having either been joined or detached, then a\nwarning will be issued.\n\nCalling \"->join()\" or \"->detach()\" on an already joined thread will cause an error to be\nthrown.\n\n$thr->detach()\nMakes the thread unjoinable, and causes any eventual return value to be discarded.  When\nthe program exits, any detached threads that are still running are silently terminated.\n\nIf the program exits without all threads having either been joined or detached, then a\nwarning will be issued.\n\nCalling \"->join()\" or \"->detach()\" on an already detached thread will cause an error to\nbe thrown.\n\nthreads->detach()\nClass method that allows a thread to detach itself.\n\nthreads->self()\nClass method that allows a thread to obtain its own threads object.\n\n$thr->tid()\nReturns the ID of the thread.  Thread IDs are unique integers with the main thread in a\nprogram being 0, and incrementing by 1 for every thread created.\n\nthreads->tid()\nClass method that allows a thread to obtain its own ID.\n\n\"$thr\"\nIf you add the \"stringify\" import option to your \"use threads\" declaration, then using a\nthreads object in a string or a string context (e.g., as a hash key) will cause its ID to\nbe used as the value:\n\nuse threads qw(stringify);\n\nmy $thr = threads->create(...);\nprint(\"Thread $thr started\\n\");  # Prints: Thread 1 started\n\nthreads->object($tid)\nThis will return the threads object for the active thread associated with the specified\nthread ID.  If $tid is the value for the current thread, then this call works the same as\n\"->self()\".  Otherwise, returns \"undef\" if there is no thread associated with the TID, if\nthe thread is joined or detached, if no TID is specified or if the specified TID is\nundef.\n\nthreads->yield()\nThis is a suggestion to the OS to let this thread yield CPU time to other threads.  What\nactually happens is highly dependent upon the underlying thread implementation.\n\nYou may do \"use threads qw(yield)\", and then just use \"yield()\" in your code.\n\nthreads->list()\nthreads->list(threads::all)\nthreads->list(threads::running)\nthreads->list(threads::joinable)\nWith no arguments (or using \"threads::all\") and in a list context, returns a list of all\nnon-joined, non-detached threads objects.  In a scalar context, returns a count of the\nsame.\n\nWith a true argument (using \"threads::running\"), returns a list of all non-joined, non-\ndetached threads objects that are still running.\n\nWith a false argument (using \"threads::joinable\"), returns a list of all non-joined, non-\ndetached threads objects that have finished running (i.e., for which \"->join()\" will not\nblock).\n\n$thr1->equal($thr2)\nTests if two threads objects are the same thread or not.  This is overloaded to the more\nnatural forms:\n\nif ($thr1 == $thr2) {\nprint(\"Threads are the same\\n\");\n}\n# or\nif ($thr1 != $thr2) {\nprint(\"Threads differ\\n\");\n}\n\n(Thread comparison is based on thread IDs.)\n\nasync BLOCK;\n\"async\" creates a thread to execute the block immediately following it.  This block is\ntreated as an anonymous subroutine, and so must have a semicolon after the closing brace.\nLike \"threads->create()\", \"async\" returns a threads object.\n\n$thr->error()\nThreads are executed in an \"eval\" context.  This method will return \"undef\" if the thread\nterminates normally.  Otherwise, it returns the value of $@ associated with the thread's\nexecution status in its \"eval\" context.\n\n$thr->handle()\nThis private method returns a pointer (i.e., the memory location expressed as an unsigned\ninteger) to the internal thread structure associated with a threads object.  For Win32,\nthis is a pointer to the \"HANDLE\" value returned by \"CreateThread\" (i.e., \"HANDLE *\");\nfor other platforms, it is a pointer to the \"pthreadt\" structure used in the\n\"pthreadcreate\" call (i.e., \"pthreadt *\").\n\nThis method is of no use for general Perl threads programming.  Its intent is to provide\nother (XS-based) thread modules with the capability to access, and possibly manipulate,\nthe underlying thread structure associated with a Perl thread.\n\nthreads->handle()\nClass method that allows a thread to obtain its own handle.\n",
                "subsections": []
            },
            "EXITING A THREAD": {
                "content": "The usual method for terminating a thread is to return() from the entry point function with\nthe appropriate return value(s).\n\nthreads->exit()\nIf needed, a thread can be exited at any time by calling \"threads->exit()\".  This will\ncause the thread to return \"undef\" in a scalar context, or the empty list in a list\ncontext.\n\nWhen called from the main thread, this behaves the same as exit(0).\n\nthreads->exit(status)\nWhen called from a thread, this behaves like \"threads->exit()\" (i.e., the exit status\ncode is ignored).\n\nWhen called from the main thread, this behaves the same as \"exit(status)\".\n",
                "subsections": [
                    {
                        "name": "die()",
                        "content": "Calling \"die()\" in a thread indicates an abnormal exit for the thread.  Any $SIG{DIE}\nhandler in the thread will be called first, and then the thread will exit with a warning\nmessage that will contain any arguments passed in the \"die()\" call.\n\nexit(status)\nCalling exit() inside a thread causes the whole application to terminate.  Because of\nthis, the use of \"exit()\" inside threaded code, or in modules that might be used in\nthreaded applications, is strongly discouraged.\n\nIf \"exit()\" really is needed, then consider using the following:\n\nthreads->exit() if threads->can('exit');   # Thread friendly\nexit(status);\n\nuse threads 'exit' => 'threadsonly'\nThis globally overrides the default behavior of calling \"exit()\" inside a thread, and\neffectively causes such calls to behave the same as \"threads->exit()\".  In other words,\nwith this setting, calling \"exit()\" causes only the thread to terminate.\n\nBecause of its global effect, this setting should not be used inside modules or the like.\n\nThe main thread is unaffected by this setting.\n\nthreads->create({'exit' => 'threadonly'}, ...)\nThis overrides the default behavior of \"exit()\" inside the newly created thread only.\n\n$thr->setthreadexitonly(boolean)\nThis can be used to change the exit thread only behavior for a thread after it has been\ncreated.  With a true argument, \"exit()\" will cause only the thread to exit.  With a\nfalse argument, \"exit()\" will terminate the application.\n\nThe main thread is unaffected by this call.\n\nthreads->setthreadexitonly(boolean)\nClass method for use inside a thread to change its own behavior for \"exit()\".\n\nThe main thread is unaffected by this call.\n"
                    }
                ]
            },
            "THREAD STATE": {
                "content": "The following boolean methods are useful in determining the state of a thread.\n\n$thr->isrunning()\nReturns true if a thread is still running (i.e., if its entry point function has not yet\nfinished or exited).\n\n$thr->isjoinable()\nReturns true if the thread has finished running, is not detached and has not yet been\njoined.  In other words, the thread is ready to be joined, and a call to \"$thr->join()\"\nwill not block.\n\n$thr->isdetached()\nReturns true if the thread has been detached.\n\nthreads->isdetached()\nClass method that allows a thread to determine whether or not it is detached.\n",
                "subsections": []
            },
            "THREAD CONTEXT": {
                "content": "As with subroutines, the type of value returned from a thread's entry point function may be\ndetermined by the thread's context:  list, scalar or void.  The thread's context is\ndetermined at thread creation.  This is necessary so that the context is available to the\nentry point function via wantarray().  The thread may then specify a value of the appropriate\ntype to be returned from \"->join()\".\n",
                "subsections": [
                    {
                        "name": "Explicit context",
                        "content": "Because thread creation and thread joining may occur in different contexts, it may be\ndesirable to state the context explicitly to the thread's entry point function.  This may be\ndone by calling \"->create()\" with a hash reference as the first argument:\n\nmy $thr = threads->create({'context' => 'list'}, \\&foo);\n...\nmy @results = $thr->join();\n\nIn the above, the threads object is returned to the parent thread in scalar context, and the\nthread's entry point function \"foo\" will be called in list (array) context such that the\nparent thread can receive a list (array) from the \"->join()\" call.  ('array' is synonymous\nwith 'list'.)\n\nSimilarly, if you need the threads object, but your thread will not be returning a value\n(i.e., void context), you would do the following:\n\nmy $thr = threads->create({'context' => 'void'}, \\&foo);\n...\n$thr->join();\n\nThe context type may also be used as the key in the hash reference followed by a true value:\n\nthreads->create({'scalar' => 1}, \\&foo);\n...\nmy ($thr) = threads->list();\nmy $result = $thr->join();\n"
                    },
                    {
                        "name": "Implicit context",
                        "content": "If not explicitly stated, the thread's context is implied from the context of the\n\"->create()\" call:\n\n# Create thread in list context\nmy ($thr) = threads->create(...);\n\n# Create thread in scalar context\nmy $thr = threads->create(...);\n\n# Create thread in void context\nthreads->create(...);\n"
                    },
                    {
                        "name": "$thr->wantarray()",
                        "content": "This returns the thread's context in the same manner as wantarray().\n"
                    },
                    {
                        "name": "threads->wantarray()",
                        "content": "Class method to return the current thread's context.  This returns the same value as running\nwantarray() inside the current thread's entry point function.\n"
                    }
                ]
            },
            "THREAD STACK SIZE": {
                "content": "The default per-thread stack size for different platforms varies significantly, and is almost\nalways far more than is needed for most applications.  On Win32, Perl's makefile explicitly\nsets the default stack to 16 MB; on most other platforms, the system default is used, which\nagain may be much larger than is needed.\n\nBy tuning the stack size to more accurately reflect your application's needs, you may\nsignificantly reduce your application's memory usage, and increase the number of\nsimultaneously running threads.\n\nNote that on Windows, address space allocation granularity is 64 KB, therefore, setting the\nstack smaller than that on Win32 Perl will not save any more memory.\n\nthreads->getstacksize();\nReturns the current default per-thread stack size.  The default is zero, which means the\nsystem default stack size is currently in use.\n\n$size = $thr->getstacksize();\nReturns the stack size for a particular thread.  A return value of zero indicates the\nsystem default stack size was used for the thread.\n\n$oldsize = threads->setstacksize($newsize);\nSets a new default per-thread stack size, and returns the previous setting.\n\nSome platforms have a minimum thread stack size.  Trying to set the stack size below this\nvalue will result in a warning, and the minimum stack size will be used.\n\nSome Linux platforms have a maximum stack size.  Setting too large of a stack size will\ncause thread creation to fail.\n\nIf needed, $newsize will be rounded up to the next multiple of the memory page size\n(usually 4096 or 8192).\n\nThreads created after the stack size is set will then either call\n\"pthreadattrsetstacksize()\" (for pthreads platforms), or supply the stack size to\n\"CreateThread()\" (for Win32 Perl).\n\n(Obviously, this call does not affect any currently extant threads.)\n\nuse threads ('stacksize' => VALUE);\nThis sets the default per-thread stack size at the start of the application.\n\n$ENV{'PERL5ITHREADSSTACKSIZE'}\nThe default per-thread stack size may be set at the start of the application through the\nuse of the environment variable \"PERL5ITHREADSSTACKSIZE\":\n\nPERL5ITHREADSSTACKSIZE=1048576\nexport PERL5ITHREADSSTACKSIZE\nperl -e'use threads; print(threads->getstacksize(), \"\\n\")'\n\nThis value overrides any \"stacksize\" parameter given to \"use threads\".  Its primary\npurpose is to permit setting the per-thread stack size for legacy threaded applications.\n\nthreads->create({'stacksize' => VALUE}, FUNCTION, ARGS)\nTo specify a particular stack size for any individual thread, call \"->create()\" with a\nhash reference as the first argument:\n\nmy $thr = threads->create({'stacksize' => 32*4096},\n\\&foo, @args);\n\n$thr2 = $thr1->create(FUNCTION, ARGS)\nThis creates a new thread ($thr2) that inherits the stack size from an existing thread\n($thr1).  This is shorthand for the following:\n\nmy $stacksize = $thr1->getstacksize();\nmy $thr2 = threads->create({'stacksize' => $stacksize},\nFUNCTION, ARGS);\n",
                "subsections": []
            },
            "THREAD SIGNALLING": {
                "content": "When safe signals is in effect (the default behavior - see \"Unsafe signals\" for more\ndetails), then signals may be sent and acted upon by individual threads.\n\n$thr->kill('SIG...');\nSends the specified signal to the thread.  Signal names and (positive) signal numbers are\nthe same as those supported by kill().  For example, 'SIGTERM', 'TERM' and (depending on\nthe OS) 15 are all valid arguments to \"->kill()\".\n\nReturns the thread object to allow for method chaining:\n\n$thr->kill('SIG...')->join();\n\nSignal handlers need to be set up in the threads for the signals they are expected to act\nupon.  Here's an example for cancelling a thread:\n\nuse threads;\n\nsub thrfunc\n{\n# Thread 'cancellation' signal handler\n$SIG{'KILL'} = sub { threads->exit(); };\n\n...\n}\n\n# Create a thread\nmy $thr = threads->create('thrfunc');\n\n...\n\n# Signal the thread to terminate, and then detach\n# it so that it will get cleaned up automatically\n$thr->kill('KILL')->detach();\n\nHere's another simplistic example that illustrates the use of thread signalling in\nconjunction with a semaphore to provide rudimentary suspend and resume capabilities:\n\nuse threads;\nuse Thread::Semaphore;\n\nsub thrfunc\n{\nmy $sema = shift;\n\n# Thread 'suspend/resume' signal handler\n$SIG{'STOP'} = sub {\n$sema->down();      # Thread suspended\n$sema->up();        # Thread resumes\n};\n\n...\n}\n\n# Create a semaphore and pass it to a thread\nmy $sema = Thread::Semaphore->new();\nmy $thr = threads->create('thrfunc', $sema);\n\n# Suspend the thread\n$sema->down();\n$thr->kill('STOP');\n\n...\n\n# Allow the thread to continue\n$sema->up();\n\nCAVEAT:  The thread signalling capability provided by this module does not actually send\nsignals via the OS.  It emulates signals at the Perl-level such that signal handlers are\ncalled in the appropriate thread.  For example, sending \"$thr->kill('STOP')\" does not\nactually suspend a thread (or the whole process), but does cause a $SIG{'STOP'} handler to be\ncalled in that thread (as illustrated above).\n\nAs such, signals that would normally not be appropriate to use in the \"kill()\" command (e.g.,\n\"kill('KILL', $$)\") are okay to use with the \"->kill()\" method (again, as illustrated above).\n\nCorrespondingly, sending a signal to a thread does not disrupt the operation the thread is\ncurrently working on:  The signal will be acted upon after the current operation has\ncompleted.  For instance, if the thread is stuck on an I/O call, sending it a signal will not\ncause the I/O call to be interrupted such that the signal is acted up immediately.\n\nSending a signal to a terminated/finished thread is ignored.\n",
                "subsections": []
            },
            "WARNINGS": {
                "content": "Perl exited with active threads:\nIf the program exits without all threads having either been joined or detached, then this\nwarning will be issued.\n\nNOTE:  If the main thread exits, then this warning cannot be suppressed using \"no\nwarnings 'threads';\" as suggested below.\n\nThread creation failed: pthreadcreate returned #\nSee the appropriate man page for \"pthreadcreate\" to determine the actual cause for the\nfailure.\n\nThread # terminated abnormally: ...\nA thread terminated in some manner other than just returning from its entry point\nfunction, or by using \"threads->exit()\".  For example, the thread may have terminated\nbecause of an error, or by using \"die\".\n\nUsing minimum thread stack size of #\nSome platforms have a minimum thread stack size.  Trying to set the stack size below this\nvalue will result in the above warning, and the stack size will be set to the minimum.\n\nThread creation failed: pthreadattrsetstacksize(SIZE) returned 22\nThe specified SIZE exceeds the system's maximum stack size.  Use a smaller value for the\nstack size.\n\nIf needed, thread warnings can be suppressed by using:\n\nno warnings 'threads';\n\nin the appropriate scope.\n",
                "subsections": []
            },
            "ERRORS": {
                "content": "This Perl not built to support threads\nThe particular copy of Perl that you're trying to use was not built using the\n\"useithreads\" configuration option.\n\nHaving threads support requires all of Perl and all of the XS modules in the Perl\ninstallation to be rebuilt; it is not just a question of adding the threads module (i.e.,\nthreaded and non-threaded Perls are binary incompatible).\n\nCannot change stack size of an existing thread\nThe stack size of currently extant threads cannot be changed, therefore, the following\nresults in the above error:\n\n$thr->setstacksize($size);\n\nCannot signal threads without safe signals\nSafe signals must be in effect to use the \"->kill()\" signalling method.  See \"Unsafe\nsignals\" for more details.\n\nUnrecognized signal name: ...\nThe particular copy of Perl that you're trying to use does not support the specified\nsignal being used in a \"->kill()\" call.\n",
                "subsections": []
            },
            "BUGS AND LIMITATIONS": {
                "content": "Before you consider posting a bug report, please consult, and possibly post a message to the\ndiscussion forum to see if what you've encountered is a known problem.\n\nThread-safe modules\nSee \"Making your module threadsafe\" in perlmod when creating modules that may be used in\nthreaded applications, especially if those modules use non-Perl data, or XS code.\n\nUsing non-thread-safe modules\nUnfortunately, you may encounter Perl modules that are not thread-safe.  For example,\nthey may crash the Perl interpreter during execution, or may dump core on termination.\nDepending on the module and the requirements of your application, it may be possible to\nwork around such difficulties.\n\nIf the module will only be used inside a thread, you can try loading the module from\ninside the thread entry point function using \"require\" (and \"import\" if needed):\n\nsub thrfunc\n{\nrequire Unsafe::Module\n# Unsafe::Module->import(...);\n\n....\n}\n\nIf the module is needed inside the main thread, try modifying your application so that\nthe module is loaded (again using \"require\" and \"->import()\") after any threads are\nstarted, and in such a way that no other threads are started afterwards.\n\nIf the above does not work, or is not adequate for your application, then file a bug\nreport on <https://rt.cpan.org/Public/> against the problematic module.\n\nMemory consumption\nOn most systems, frequent and continual creation and destruction of threads can lead to\never-increasing growth in the memory footprint of the Perl interpreter.  While it is\nsimple to just launch threads and then \"->join()\" or \"->detach()\" them, for long-lived\napplications, it is better to maintain a pool of threads, and to reuse them for the work\nneeded, using queues to notify threads of pending work.  The CPAN distribution of this\nmodule contains a simple example (examples/poolreuse.pl) illustrating the creation, use\nand monitoring of a pool of reusable threads.\n\nCurrent working directory\nOn all platforms except MSWin32, the setting for the current working directory is shared\namong all threads such that changing it in one thread (e.g., using \"chdir()\") will affect\nall the threads in the application.\n\nOn MSWin32, each thread maintains its own the current working directory setting.\n\nLocales\nPrior to Perl 5.28, locales could not be used with threads, due to various race\nconditions.  Starting in that release, on systems that implement thread-safe locale\nfunctions, threads can be used, with some caveats.  This includes Windows starting with\nVisual Studio 2005, and systems compatible with POSIX 2008.  See \"Multi-threaded\noperation\" in perllocale.\n\nEach thread (except the main thread) is started using the C locale.  The main thread is\nstarted like all other Perl programs; see \"ENVIRONMENT\" in perllocale.  You can switch\nlocales in any thread as often as you like.\n\nIf you want to inherit the parent thread's locale, you can, in the parent, set a variable\nlike so:\n\n$foo = POSIX::setlocale(LCALL, NULL);\n\nand then pass to threads->create() a sub that closes over $foo.  Then, in the child, you\nsay\n\nPOSIX::setlocale(LCALL, $foo);\n\nOr you can use the facilities in threads::shared to pass $foo; or if the environment\nhasn't changed, in the child, do\n\nPOSIX::setlocale(LCALL, \"\");\n\nEnvironment variables\nCurrently, on all platforms except MSWin32, all system calls (e.g., using \"system()\" or\nback-ticks) made from threads use the environment variable settings from the main thread.\nIn other words, changes made to %ENV in a thread will not be visible in system calls made\nby that thread.\n\nTo work around this, set environment variables as part of the system call.  For example:\n\nmy $msg = 'hello';\nsystem(\"FOO=$msg; echo \\$FOO\");   # Outputs 'hello' to STDOUT\n\nOn MSWin32, each thread maintains its own set of environment variables.\n\nCatching signals\nSignals are caught by the main thread (thread ID = 0) of a script.  Therefore, setting up\nsignal handlers in threads for purposes other than \"THREAD SIGNALLING\" as documented\nabove will not accomplish what is intended.\n\nThis is especially true if trying to catch \"SIGALRM\" in a thread.  To handle alarms in\nthreads, set up a signal handler in the main thread, and then use \"THREAD SIGNALLING\" to\nrelay the signal to the thread:\n\n# Create thread with a task that may time out\nmy $thr = threads->create(sub {\nthreads->yield();\neval {\n$SIG{ALRM} = sub { die(\"Timeout\\n\"); };\nalarm(10);\n...  # Do work here\nalarm(0);\n};\nif ($@ =~ /Timeout/) {\nwarn(\"Task in thread timed out\\n\");\n}\n};\n\n# Set signal handler to relay SIGALRM to thread\n$SIG{ALRM} = sub { $thr->kill('ALRM') };\n\n... # Main thread continues working\n\nParent-child threads\nOn some platforms, it might not be possible to destroy parent threads while there are\nstill existing child threads.\n\nUnsafe signals\nSince Perl 5.8.0, signals have been made safer in Perl by postponing their handling until\nthe interpreter is in a safe state.  See \"Safe Signals\" in perl58delta and \"Deferred\nSignals (Safe Signals)\" in perlipc for more details.\n\nSafe signals is the default behavior, and the old, immediate, unsafe signalling behavior\nis only in effect in the following situations:\n\n•   Perl has been built with \"PERLOLDSIGNALS\" (see \"perl -V\").\n\n•   The environment variable \"PERLSIGNALS\" is set to \"unsafe\" (see \"PERLSIGNALS\" in\nperlrun).\n\n•   The module Perl::Unsafe::Signals is used.\n\nIf unsafe signals is in effect, then signal handling is not thread-safe, and the\n\"->kill()\" signalling method cannot be used.\n\nIdentity of objects returned from threads\nWhen a value is returned from a thread through a \"join\" operation, the value and\neverything that it references is copied across to the joining thread, in much the same\nway that values are copied upon thread creation.  This works fine for most kinds of\nvalue, including arrays, hashes, and subroutines.  The copying recurses through array\nelements, reference scalars, variables closed over by subroutines, and other kinds of\nreference.\n\nHowever, everything referenced by the returned value is a fresh copy in the joining\nthread, even if a returned object had in the child thread been a copy of something that\npreviously existed in the parent thread.  After joining, the parent will therefore have a\nduplicate of each such object.  This sometimes matters, especially if the object gets\nmutated; this can especially matter for private data to which a returned subroutine\nprovides access.\n\nReturning blessed objects from threads\nReturning blessed objects from threads does not work.  Depending on the classes involved,\nyou may be able to work around this by returning a serialized version of the object\n(e.g., using Data::Dumper or Storable), and then reconstituting it in the joining thread.\nIf you're using Perl 5.10.0 or later, and if the class supports shared objects, you can\npass them via shared queues.\n\nEND blocks in threads\nIt is possible to add END blocks to threads by using require or eval with the appropriate\ncode.  These \"END\" blocks will then be executed when the thread's interpreter is\ndestroyed (i.e., either during a \"->join()\" call, or at program termination).\n\nHowever, calling any threads methods in such an \"END\" block will most likely fail (e.g.,\nthe application may hang, or generate an error) due to mutexes that are needed to control\nfunctionality within the threads module.\n\nFor this reason, the use of \"END\" blocks in threads is strongly discouraged.\n\nOpen directory handles\nIn perl 5.14 and higher, on systems other than Windows that do not support the \"fchdir\" C\nfunction, directory handles (see opendir) will not be copied to new threads. You can use\nthe \"dfchdir\" variable in Config.pm to determine whether your system supports it.\n\nIn prior perl versions, spawning threads with open directory handles would crash the\ninterpreter.  [perl #75154] <https://rt.perl.org/rt3/Public/Bug/Display.html?id=75154>\n\nDetached threads and global destruction\nIf the main thread exits while there are detached threads which are still running, then\nPerl's global destruction phase is not executed because otherwise certain global\nstructures that control the operation of threads and that are allocated in the main\nthread's memory may get destroyed before the detached thread is destroyed.\n\nIf you are using any code that requires the execution of the global destruction phase for\nclean up (e.g., removing temp files), then do not use detached threads, but rather join\nall threads before exiting the program.\n\nPerl Bugs and the CPAN Version of threads\nSupport for threads extends beyond the code in this module (i.e., threads.pm and\nthreads.xs), and into the Perl interpreter itself.  Older versions of Perl contain bugs\nthat may manifest themselves despite using the latest version of threads from CPAN.\nThere is no workaround for this other than upgrading to the latest version of Perl.\n\nEven with the latest version of Perl, it is known that certain constructs with threads\nmay result in warning messages concerning leaked scalars or unreferenced scalars.\nHowever, such warnings are harmless, and may safely be ignored.\n\nYou can search for threads related bug reports at <https://rt.cpan.org/Public/>.  If\nneeded submit any new bugs, problems, patches, etc. to:\n<https://rt.cpan.org/Public/Dist/Display.html?Name=threads>\n",
                "subsections": []
            },
            "REQUIREMENTS": {
                "content": "Perl 5.8.0 or later\n",
                "subsections": []
            },
            "SEE ALSO": {
                "content": "threads on MetaCPAN: <https://metacpan.org/release/threads>\n\nCode repository for CPAN distribution: <https://github.com/Dual-Life/threads>\n\nthreads::shared, perlthrtut\n\n<https://www.perl.com/pub/a/2002/06/11/threads.html> and\n<https://www.perl.com/pub/a/2002/09/04/threads.html>\n\nPerl threads mailing list: <https://lists.perl.org/list/ithreads.html>\n\nStack size discussion: <https://www.perlmonks.org/?nodeid=532956>\n\nSample code in the examples directory of this distribution on CPAN.\n",
                "subsections": []
            },
            "AUTHOR": {
                "content": "Artur Bergman <sky AT crucially DOT net>\n\nCPAN version produced by Jerry D. Hedden <jdhedden AT cpan DOT org>\n",
                "subsections": []
            },
            "LICENSE": {
                "content": "threads is released under the same license as Perl.\n",
                "subsections": []
            },
            "ACKNOWLEDGEMENTS": {
                "content": "Richard Soderberg <perl AT crystalflame DOT net> - Helping me out tons, trying to find\nreasons for races and other weird bugs!\n\nSimon Cozens <simon AT brecon DOT co DOT uk> - Being there to answer zillions of annoying\nquestions\n\nRocco Caputo <troc AT netrus DOT net>\n\nVipul Ved Prakash <mail AT vipul DOT net> - Helping with debugging\n\nDean Arnold <darnold AT presicient DOT com> - Stack size API\n\n\n\nperl v5.34.0                                 2025-07-25                               threads(3perl)",
                "subsections": []
            }
        }
    }
}