{
    "mode": "man",
    "parameter": "PERLTHRTUT",
    "section": "1",
    "url": "https://www.chedong.com/phpMan.php/man/PERLTHRTUT/1/json",
    "generated": "2026-06-03T09:46:11Z",
    "sections": {
        "NAME": {
            "content": "perlthrtut - Tutorial on threads in Perl\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "This tutorial describes the use of Perl interpreter threads (sometimes referred to as\nithreads).  In this model, each thread runs in its own Perl interpreter, and any data sharing\nbetween threads must be explicit.  The user-level interface for ithreads uses the threads\nclass.\n\nNOTE: There was another older Perl threading flavor called the 5.005 model that used the\nthreads class.  This old model was known to have problems, is deprecated, and was removed for\nrelease 5.10.  You are strongly encouraged to migrate any existing 5.005 threads code to the\nnew model as soon as possible.\n\nYou can see which (or neither) threading flavour you have by running \"perl -V\" and looking at\nthe \"Platform\" section.  If you have \"useithreads=define\" you have ithreads, if you have\n\"use5005threads=define\" you have 5.005 threads.  If you have neither, you don't have any\nthread support built in.  If you have both, you are in trouble.\n\nThe threads and threads::shared modules are included in the core Perl distribution.\nAdditionally, they are maintained as a separate modules on CPAN, so you can check there for\nany updates.\n",
            "subsections": [
                {
                    "name": "What Is A Thread Anyway?",
                    "content": "A thread is a flow of control through a program with a single execution point.\n\nSounds an awful lot like a process, doesn't it? Well, it should.  Threads are one of the\npieces of a process.  Every process has at least one thread and, up until now, every process\nrunning Perl had only one thread.  With 5.8, though, you can create extra threads.  We're\ngoing to show you how, when, and why.\n"
                },
                {
                    "name": "Threaded Program Models",
                    "content": "There are three basic ways that you can structure a threaded program.  Which model you choose\ndepends on what you need your program to do.  For many non-trivial threaded programs, you'll\nneed to choose different models for different pieces of your program.\n"
                },
                {
                    "name": "Boss/Worker",
                    "content": "The boss/worker model usually has one boss thread and one or more worker threads.  The boss\nthread gathers or generates tasks that need to be done, then parcels those tasks out to the\nappropriate worker thread.\n\nThis model is common in GUI and server programs, where a main thread waits for some event and\nthen passes that event to the appropriate worker threads for processing.  Once the event has\nbeen passed on, the boss thread goes back to waiting for another event.\n\nThe boss thread does relatively little work.  While tasks aren't necessarily performed faster\nthan with any other method, it tends to have the best user-response times.\n"
                },
                {
                    "name": "Work Crew",
                    "content": "In the work crew model, several threads are created that do essentially the same thing to\ndifferent pieces of data.  It closely mirrors classical parallel processing and vector\nprocessors, where a large array of processors do the exact same thing to many pieces of data.\n\nThis model is particularly useful if the system running the program will distribute multiple\nthreads across different processors.  It can also be useful in ray tracing or rendering\nengines, where the individual threads can pass on interim results to give the user visual\nfeedback.\n"
                },
                {
                    "name": "Pipeline",
                    "content": "The pipeline model divides up a task into a series of steps, and passes the results of one\nstep on to the thread processing the next.  Each thread does one thing to each piece of data\nand passes the results to the next thread in line.\n\nThis model makes the most sense if you have multiple processors so two or more threads will\nbe executing in parallel, though it can often make sense in other contexts as well.  It tends\nto keep the individual tasks small and simple, as well as allowing some parts of the pipeline\nto block (on I/O or system calls, for example) while other parts keep going.  If you're\nrunning different parts of the pipeline on different processors you may also take advantage\nof the caches on each processor.\n\nThis model is also handy for a form of recursive programming where, rather than having a\nsubroutine call itself, it instead creates another thread.  Prime and Fibonacci generators\nboth map well to this form of the pipeline model. (A version of a prime number generator is\npresented later on.)\n"
                },
                {
                    "name": "What kind of threads are Perl threads?",
                    "content": "If you have experience with other thread implementations, you might find that things aren't\nquite what you expect.  It's very important to remember when dealing with Perl threads that\nPerl Threads Are Not X Threads for all values of X.  They aren't POSIX threads, or\nDecThreads, or Java's Green threads, or Win32 threads.  There are similarities, and the broad\nconcepts are the same, but if you start looking for implementation details you're going to be\neither disappointed or confused.  Possibly both.\n\nThis is not to say that Perl threads are completely different from everything that's ever\ncome before. They're not.  Perl's threading model owes a lot to other thread models,\nespecially POSIX.  Just as Perl is not C, though, Perl threads are not POSIX threads.  So if\nyou find yourself looking for mutexes, or thread priorities, it's time to step back a bit and\nthink about what you want to do and how Perl can do it.\n\nHowever, it is important to remember that Perl threads cannot magically do things unless your\noperating system's threads allow it. So if your system blocks the entire process on\n\"sleep()\", Perl usually will, as well.\n"
                },
                {
                    "name": "Perl Threads Are Different.",
                    "content": ""
                },
                {
                    "name": "Thread-Safe Modules",
                    "content": "The addition of threads has changed Perl's internals substantially. There are implications\nfor people who write modules with XS code or external libraries. However, since Perl data is\nnot shared among threads by default, Perl modules stand a high chance of being thread-safe or\ncan be made thread-safe easily.  Modules that are not tagged as thread-safe should be tested\nor code reviewed before being used in production code.\n\nNot all modules that you might use are thread-safe, and you should always assume a module is\nunsafe unless the documentation says otherwise.  This includes modules that are distributed\nas part of the core.  Threads are a relatively new feature, and even some of the standard\nmodules aren't thread-safe.\n\nEven if a module is thread-safe, it doesn't mean that the module is optimized to work well\nwith threads. A module could possibly be rewritten to utilize the new features in threaded\nPerl to increase performance in a threaded environment.\n\nIf you're using a module that's not thread-safe for some reason, you can protect yourself by\nusing it from one, and only one thread at all.  If you need multiple threads to access such a\nmodule, you can use semaphores and lots of programming discipline to control access to it.\nSemaphores are covered in \"Basic semaphores\".\n\nSee also \"Thread-Safety of System Libraries\".\n"
                },
                {
                    "name": "Thread Basics",
                    "content": "The threads module provides the basic functions you need to write threaded programs.  In the\nfollowing sections, we'll cover the basics, showing you what you need to do to create a\nthreaded program.   After that, we'll go over some of the features of the threads module that\nmake threaded programming easier.\n"
                },
                {
                    "name": "Basic Thread Support",
                    "content": "Thread support is a Perl compile-time option. It's something that's turned on or off when\nPerl is built at your site, rather than when your programs are compiled. If your Perl wasn't\ncompiled with thread support enabled, then any attempt to use threads will fail.\n\nYour programs can use the Config module to check whether threads are enabled. If your program\ncan't run without them, you can say something like:\n\nuse Config;\n$Config{useithreads} or\ndie('Recompile Perl with threads to run this program.');\n\nA possibly-threaded program using a possibly-threaded module might have code like this:\n\nuse Config;\nuse MyMod;\n\nBEGIN {\nif ($Config{useithreads}) {\n# We have threads\nrequire MyModthreaded;\nimport MyModthreaded;\n} else {\nrequire MyModunthreaded;\nimport MyModunthreaded;\n}\n}\n\nSince code that runs both with and without threads is usually pretty messy, it's best to\nisolate the thread-specific code in its own module.  In our example above, that's what\n\"MyModthreaded\" is, and it's only imported if we're running on a threaded Perl.\n"
                },
                {
                    "name": "A Note about the Examples",
                    "content": "In a real situation, care should be taken that all threads are finished executing before the\nprogram exits.  That care has not been taken in these examples in the interest of simplicity.\nRunning these examples as is will produce error messages, usually caused by the fact that\nthere are still threads running when the program exits.  You should not be alarmed by this.\n"
                },
                {
                    "name": "Creating Threads",
                    "content": "The threads module provides the tools you need to create new threads.  Like any other module,\nyou need to tell Perl that you want to use it; \"use threads;\" imports all the pieces you need\nto create basic threads.\n\nThe simplest, most straightforward way to create a thread is with \"create()\":\n\nuse threads;\n\nmy $thr = threads->create(\\&sub1);\n\nsub sub1 {\nprint(\"In the thread\\n\");\n}\n\nThe \"create()\" method takes a reference to a subroutine and creates a new thread that starts\nexecuting in the referenced subroutine.  Control then passes both to the subroutine and the\ncaller.\n\nIf you need to, your program can pass parameters to the subroutine as part of the thread\nstartup.  Just include the list of parameters as part of the \"threads->create()\" call, like\nthis:\n\nuse threads;\n\nmy $Param3 = 'foo';\nmy $thr1 = threads->create(\\&sub1, 'Param 1', 'Param 2', $Param3);\nmy @ParamList = (42, 'Hello', 3.14);\nmy $thr2 = threads->create(\\&sub1, @ParamList);\nmy $thr3 = threads->create(\\&sub1, qw(Param1 Param2 Param3));\n\nsub sub1 {\nmy @InboundParameters = @;\nprint(\"In the thread\\n\");\nprint('Got parameters >', join('<>',@InboundParameters), \"<\\n\");\n}\n\nThe last example illustrates another feature of threads.  You can spawn off several threads\nusing the same subroutine.  Each thread executes the same subroutine, but in a separate\nthread with a separate environment and potentially separate arguments.\n\n\"new()\" is a synonym for \"create()\".\n"
                },
                {
                    "name": "Waiting For A Thread To Exit",
                    "content": "Since threads are also subroutines, they can return values.  To wait for a thread to exit and\nextract any values it might return, you can use the \"join()\" method:\n\nuse threads;\n\nmy ($thr) = threads->create(\\&sub1);\n\nmy @ReturnData = $thr->join();\nprint('Thread returned ', join(', ', @ReturnData), \"\\n\");\n\nsub sub1 { return ('Fifty-six', 'foo', 2); }\n\nIn the example above, the \"join()\" method returns as soon as the thread ends.  In addition to\nwaiting for a thread to finish and gathering up any values that the thread might have\nreturned, \"join()\" also performs any OS cleanup necessary for the thread.  That cleanup might\nbe important, especially for long-running programs that spawn lots of threads.  If you don't\nwant the return values and don't want to wait for the thread to finish, you should call the\n\"detach()\" method instead, as described next.\n\nNOTE: In the example above, the thread returns a list, thus necessitating that the thread\ncreation call be made in list context (i.e., \"my ($thr)\").  See \"$thr->join()\" in threads and\n\"THREAD CONTEXT\" in threads for more details on thread context and return values.\n"
                },
                {
                    "name": "Ignoring A Thread",
                    "content": "\"join()\" does three things: it waits for a thread to exit, cleans up after it, and returns\nany data the thread may have produced.  But what if you're not interested in the thread's\nreturn values, and you don't really care when the thread finishes? All you want is for the\nthread to get cleaned up after when it's done.\n\nIn this case, you use the \"detach()\" method.  Once a thread is detached, it'll run until it's\nfinished; then Perl will clean up after it automatically.\n\nuse threads;\n\nmy $thr = threads->create(\\&sub1);   # Spawn the thread\n\n$thr->detach();   # Now we officially don't care any more\n\nsleep(15);        # Let thread run for awhile\n\nsub sub1 {\nmy $count = 0;\nwhile (1) {\n$count++;\nprint(\"\\$count is $count\\n\");\nsleep(1);\n}\n}\n\nOnce a thread is detached, it may not be joined, and any return data that it might have\nproduced (if it was done and waiting for a join) is lost.\n\n\"detach()\" can also be called as a class method to allow a thread to detach itself:\n\nuse threads;\n\nmy $thr = threads->create(\\&sub1);\n\nsub sub1 {\nthreads->detach();\n# Do more work\n}\n"
                },
                {
                    "name": "Process and Thread Termination",
                    "content": "With threads one must be careful to make sure they all have a chance to run to completion,\nassuming that is what you want.\n\nAn action that terminates a process will terminate all running threads.  die() and exit()\nhave this property, and perl does an exit when the main thread exits, perhaps implicitly by\nfalling off the end of your code, even if that's not what you want.\n\nAs an example of this case, this code prints the message \"Perl exited with active threads: 2\nrunning and unjoined\":\n\nuse threads;\nmy $thr1 = threads->new(\\&thrsub, \"test1\");\nmy $thr2 = threads->new(\\&thrsub, \"test2\");\nsub thrsub {\nmy ($message) = @;\nsleep 1;\nprint \"thread $message\\n\";\n}\n\nBut when the following lines are added at the end:\n\n$thr1->join();\n$thr2->join();\n\nit prints two lines of output, a perhaps more useful outcome.\n"
                },
                {
                    "name": "Threads And Data",
                    "content": "Now that we've covered the basics of threads, it's time for our next topic: Data.  Threading\nintroduces a couple of complications to data access that non-threaded programs never need to\nworry about.\n"
                },
                {
                    "name": "Shared And Unshared Data",
                    "content": "The biggest difference between Perl ithreads and the old 5.005 style threading, or for that\nmatter, to most other threading systems out there, is that by default, no data is shared.\nWhen a new Perl thread is created, all the data associated with the current thread is copied\nto the new thread, and is subsequently private to that new thread!  This is similar in feel\nto what happens when a Unix process forks, except that in this case, the data is just copied\nto a different part of memory within the same process rather than a real fork taking place.\n\nTo make use of threading, however, one usually wants the threads to share at least some data\nbetween themselves. This is done with the threads::shared module and the \":shared\" attribute:\n\nuse threads;\nuse threads::shared;\n\nmy $foo :shared = 1;\nmy $bar = 1;\nthreads->create(sub { $foo++; $bar++; })->join();\n\nprint(\"$foo\\n\");  # Prints 2 since $foo is shared\nprint(\"$bar\\n\");  # Prints 1 since $bar is not shared\n\nIn the case of a shared array, all the array's elements are shared, and for a shared hash,\nall the keys and values are shared. This places restrictions on what may be assigned to\nshared array and hash elements: only simple values or references to shared variables are\nallowed - this is so that a private variable can't accidentally become shared. A bad\nassignment will cause the thread to die. For example:\n\nuse threads;\nuse threads::shared;\n\nmy $var          = 1;\nmy $svar :shared = 2;\nmy %hash :shared;\n\n... create some threads ...\n\n$hash{a} = 1;       # All threads see exists($hash{a})\n# and $hash{a} == 1\n$hash{a} = $var;    # okay - copy-by-value: same effect as previous\n$hash{a} = $svar;   # okay - copy-by-value: same effect as previous\n$hash{a} = \\$svar;  # okay - a reference to a shared variable\n$hash{a} = \\$var;   # This will die\ndelete($hash{a});   # okay - all threads will see !exists($hash{a})\n\nNote that a shared variable guarantees that if two or more threads try to modify it at the\nsame time, the internal state of the variable will not become corrupted. However, there are\nno guarantees beyond this, as explained in the next section.\n"
                },
                {
                    "name": "Thread Pitfalls: Races",
                    "content": "While threads bring a new set of useful tools, they also bring a number of pitfalls.  One\npitfall is the race condition:\n\nuse threads;\nuse threads::shared;\n\nmy $x :shared = 1;\nmy $thr1 = threads->create(\\&sub1);\nmy $thr2 = threads->create(\\&sub2);\n\n$thr1->join();\n$thr2->join();\nprint(\"$x\\n\");\n\nsub sub1 { my $foo = $x; $x = $foo + 1; }\nsub sub2 { my $bar = $x; $x = $bar + 1; }\n\nWhat do you think $x will be? The answer, unfortunately, is it depends. Both \"sub1()\" and\n\"sub2()\" access the global variable $x, once to read and once to write.  Depending on factors\nranging from your thread implementation's scheduling algorithm to the phase of the moon, $x\ncan be 2 or 3.\n\nRace conditions are caused by unsynchronized access to shared data.  Without explicit\nsynchronization, there's no way to be sure that nothing has happened to the shared data\nbetween the time you access it and the time you update it.  Even this simple code fragment\nhas the possibility of error:\n\nuse threads;\nmy $x :shared = 2;\nmy $y :shared;\nmy $z :shared;\nmy $thr1 = threads->create(sub { $y = $x; $x = $y + 1; });\nmy $thr2 = threads->create(sub { $z = $x; $x = $z + 1; });\n$thr1->join();\n$thr2->join();\n\nTwo threads both access $x.  Each thread can potentially be interrupted at any point, or be\nexecuted in any order.  At the end, $x could be 3 or 4, and both $y and $z could be 2 or 3.\n\nEven \"$x += 5\" or \"$x++\" are not guaranteed to be atomic.\n\nWhenever your program accesses data or resources that can be accessed by other threads, you\nmust take steps to coordinate access or risk data inconsistency and race conditions. Note\nthat Perl will protect its internals from your race conditions, but it won't protect you from\nyou.\n"
                },
                {
                    "name": "Synchronization and control",
                    "content": "Perl provides a number of mechanisms to coordinate the interactions between themselves and\ntheir data, to avoid race conditions and the like.  Some of these are designed to resemble\nthe common techniques used in thread libraries such as \"pthreads\"; others are Perl-specific.\nOften, the standard techniques are clumsy and difficult to get right (such as condition\nwaits). Where possible, it is usually easier to use Perlish techniques such as queues, which\nremove some of the hard work involved.\n"
                },
                {
                    "name": "Controlling access: lock()",
                    "content": "The \"lock()\" function takes a shared variable and puts a lock on it.  No other thread may\nlock the variable until the variable is unlocked by the thread holding the lock. Unlocking\nhappens automatically when the locking thread exits the block that contains the call to the\n\"lock()\" function.  Using \"lock()\" is straightforward: This example has several threads doing\nsome calculations in parallel, and occasionally updating a running total:\n\nuse threads;\nuse threads::shared;\n\nmy $total :shared = 0;\n\nsub calc {\nwhile (1) {\nmy $result;\n# (... do some calculations and set $result ...)\n{\nlock($total);  # Block until we obtain the lock\n$total += $result;\n} # Lock implicitly released at end of scope\nlast if $result == 0;\n}\n}\n\nmy $thr1 = threads->create(\\&calc);\nmy $thr2 = threads->create(\\&calc);\nmy $thr3 = threads->create(\\&calc);\n$thr1->join();\n$thr2->join();\n$thr3->join();\nprint(\"total=$total\\n\");\n\n\"lock()\" blocks the thread until the variable being locked is available.  When \"lock()\"\nreturns, your thread can be sure that no other thread can lock that variable until the block\ncontaining the lock exits.\n\nIt's important to note that locks don't prevent access to the variable in question, only lock\nattempts.  This is in keeping with Perl's longstanding tradition of courteous programming,\nand the advisory file locking that \"flock()\" gives you.\n\nYou may lock arrays and hashes as well as scalars.  Locking an array, though, will not block\nsubsequent locks on array elements, just lock attempts on the array itself.\n\nLocks are recursive, which means it's okay for a thread to lock a variable more than once.\nThe lock will last until the outermost \"lock()\" on the variable goes out of scope. For\nexample:\n\nmy $x :shared;\ndoit();\n\nsub doit {\n{\n{\nlock($x); # Wait for lock\nlock($x); # NOOP - we already have the lock\n{\nlock($x); # NOOP\n{\nlock($x); # NOOP\nlockitsomemore();\n}\n}\n} # * Implicit unlock here *\n}\n}\n\nsub lockitsomemore {\nlock($x); # NOOP\n} # Nothing happens here\n\nNote that there is no \"unlock()\" function - the only way to unlock a variable is to allow it\nto go out of scope.\n\nA lock can either be used to guard the data contained within the variable being locked, or it\ncan be used to guard something else, like a section of code. In this latter case, the\nvariable in question does not hold any useful data, and exists only for the purpose of being\nlocked. In this respect, the variable behaves like the mutexes and basic semaphores of\ntraditional thread libraries.\n"
                },
                {
                    "name": "A Thread Pitfall: Deadlocks",
                    "content": "Locks are a handy tool to synchronize access to data, and using them properly is the key to\nsafe shared data.  Unfortunately, locks aren't without their dangers, especially when\nmultiple locks are involved.  Consider the following code:\n\nuse threads;\n\nmy $x :shared = 4;\nmy $y :shared = 'foo';\nmy $thr1 = threads->create(sub {\nlock($x);\nsleep(20);\nlock($y);\n});\nmy $thr2 = threads->create(sub {\nlock($y);\nsleep(20);\nlock($x);\n});\n\nThis program will probably hang until you kill it.  The only way it won't hang is if one of\nthe two threads acquires both locks first.  A guaranteed-to-hang version is more complicated,\nbut the principle is the same.\n\nThe first thread will grab a lock on $x, then, after a pause during which the second thread\nhas probably had time to do some work, try to grab a lock on $y.  Meanwhile, the second\nthread grabs a lock on $y, then later tries to grab a lock on $x.  The second lock attempt\nfor both threads will block, each waiting for the other to release its lock.\n\nThis condition is called a deadlock, and it occurs whenever two or more threads are trying to\nget locks on resources that the others own.  Each thread will block, waiting for the other to\nrelease a lock on a resource.  That never happens, though, since the thread with the resource\nis itself waiting for a lock to be released.\n\nThere are a number of ways to handle this sort of problem.  The best way is to always have\nall threads acquire locks in the exact same order.  If, for example, you lock variables $x,\n$y, and $z, always lock $x before $y, and $y before $z.  It's also best to hold on to locks\nfor as short a period of time to minimize the risks of deadlock.\n\nThe other synchronization primitives described below can suffer from similar problems.\n"
                },
                {
                    "name": "Queues: Passing Data Around",
                    "content": "A queue is a special thread-safe object that lets you put data in one end and take it out the\nother without having to worry about synchronization issues.  They're pretty straightforward,\nand look like this:\n\nuse threads;\nuse Thread::Queue;\n\nmy $DataQueue = Thread::Queue->new();\nmy $thr = threads->create(sub {\nwhile (my $DataElement = $DataQueue->dequeue()) {\nprint(\"Popped $DataElement off the queue\\n\");\n}\n});\n\n$DataQueue->enqueue(12);\n$DataQueue->enqueue(\"A\", \"B\", \"C\");\nsleep(10);\n$DataQueue->enqueue(undef);\n$thr->join();\n\nYou create the queue with \"Thread::Queue->new()\".  Then you can add lists of scalars onto the\nend with \"enqueue()\", and pop scalars off the front of it with \"dequeue()\".  A queue has no\nfixed size, and can grow as needed to hold everything pushed on to it.\n\nIf a queue is empty, \"dequeue()\" blocks until another thread enqueues something.  This makes\nqueues ideal for event loops and other communications between threads.\n"
                },
                {
                    "name": "Semaphores: Synchronizing Data Access",
                    "content": "Semaphores are a kind of generic locking mechanism. In their most basic form, they behave\nvery much like lockable scalars, except that they can't hold data, and that they must be\nexplicitly unlocked. In their advanced form, they act like a kind of counter, and can allow\nmultiple threads to have the lock at any one time.\n"
                },
                {
                    "name": "Basic semaphores",
                    "content": "Semaphores have two methods, \"down()\" and \"up()\": \"down()\" decrements the resource count,\nwhile \"up()\" increments it. Calls to \"down()\" will block if the semaphore's current count\nwould decrement below zero.  This program gives a quick demonstration:\n\nuse threads;\nuse Thread::Semaphore;\n\nmy $semaphore = Thread::Semaphore->new();\nmy $GlobalVariable :shared = 0;\n\n$thr1 = threads->create(\\&samplesub, 1);\n$thr2 = threads->create(\\&samplesub, 2);\n$thr3 = threads->create(\\&samplesub, 3);\n\nsub samplesub {\nmy $SubNumber = shift(@);\nmy $TryCount = 10;\nmy $LocalCopy;\nsleep(1);\nwhile ($TryCount--) {\n$semaphore->down();\n$LocalCopy = $GlobalVariable;\nprint(\"$TryCount tries left for sub $SubNumber \"\n.\"(\\$GlobalVariable is $GlobalVariable)\\n\");\nsleep(2);\n$LocalCopy++;\n$GlobalVariable = $LocalCopy;\n$semaphore->up();\n}\n}\n\n$thr1->join();\n$thr2->join();\n$thr3->join();\n\nThe three invocations of the subroutine all operate in sync.  The semaphore, though, makes\nsure that only one thread is accessing the global variable at once.\n"
                },
                {
                    "name": "Advanced Semaphores",
                    "content": "By default, semaphores behave like locks, letting only one thread \"down()\" them at a time.\nHowever, there are other uses for semaphores.\n\nEach semaphore has a counter attached to it. By default, semaphores are created with the\ncounter set to one, \"down()\" decrements the counter by one, and \"up()\" increments by one.\nHowever, we can override any or all of these defaults simply by passing in different values:\n\nuse threads;\nuse Thread::Semaphore;\n\nmy $semaphore = Thread::Semaphore->new(5);\n# Creates a semaphore with the counter set to five\n\nmy $thr1 = threads->create(\\&sub1);\nmy $thr2 = threads->create(\\&sub1);\n\nsub sub1 {\n$semaphore->down(5); # Decrements the counter by five\n# Do stuff here\n$semaphore->up(5); # Increment the counter by five\n}\n\n$thr1->detach();\n$thr2->detach();\n\nIf \"down()\" attempts to decrement the counter below zero, it blocks until the counter is\nlarge enough.  Note that while a semaphore can be created with a starting count of zero, any\n\"up()\" or \"down()\" always changes the counter by at least one, and so \"$semaphore->down(0)\"\nis the same as \"$semaphore->down(1)\".\n\nThe question, of course, is why would you do something like this? Why create a semaphore with\na starting count that's not one, or why decrement or increment it by more than one? The\nanswer is resource availability.  Many resources that you want to manage access for can be\nsafely used by more than one thread at once.\n\nFor example, let's take a GUI driven program.  It has a semaphore that it uses to synchronize\naccess to the display, so only one thread is ever drawing at once.  Handy, but of course you\ndon't want any thread to start drawing until things are properly set up.  In this case, you\ncan create a semaphore with a counter set to zero, and up it when things are ready for\ndrawing.\n\nSemaphores with counters greater than one are also useful for establishing quotas.  Say, for\nexample, that you have a number of threads that can do I/O at once.  You don't want all the\nthreads reading or writing at once though, since that can potentially swamp your I/O\nchannels, or deplete your process's quota of filehandles.  You can use a semaphore\ninitialized to the number of concurrent I/O requests (or open files) that you want at any one\ntime, and have your threads quietly block and unblock themselves.\n\nLarger increments or decrements are handy in those cases where a thread needs to check out or\nreturn a number of resources at once.\n"
                },
                {
                    "name": "Waiting for a Condition",
                    "content": "The functions \"condwait()\" and \"condsignal()\" can be used in conjunction with locks to\nnotify co-operating threads that a resource has become available. They are very similar in\nuse to the functions found in \"pthreads\". However for most purposes, queues are simpler to\nuse and more intuitive. See threads::shared for more details.\n"
                },
                {
                    "name": "Giving up control",
                    "content": "There are times when you may find it useful to have a thread explicitly give up the CPU to\nanother thread.  You may be doing something processor-intensive and want to make sure that\nthe user-interface thread gets called frequently.  Regardless, there are times that you might\nwant a thread to give up the processor.\n\nPerl's threading package provides the \"yield()\" function that does this. \"yield()\" is pretty\nstraightforward, and works like this:\n\nuse threads;\n\nsub loop {\nmy $thread = shift;\nmy $foo = 50;\nwhile($foo--) { print(\"In thread $thread\\n\"); }\nthreads->yield();\n$foo = 50;\nwhile($foo--) { print(\"In thread $thread\\n\"); }\n}\n\nmy $thr1 = threads->create(\\&loop, 'first');\nmy $thr2 = threads->create(\\&loop, 'second');\nmy $thr3 = threads->create(\\&loop, 'third');\n\nIt is important to remember that \"yield()\" is only a hint to give up the CPU, it depends on\nyour hardware, OS and threading libraries what actually happens.  On many operating systems,\nyield() is a no-op.  Therefore it is important to note that one should not build the\nscheduling of the threads around \"yield()\" calls. It might work on your platform but it won't\nwork on another platform.\n"
                },
                {
                    "name": "General Thread Utility Routines",
                    "content": "We've covered the workhorse parts of Perl's threading package, and with these tools you\nshould be well on your way to writing threaded code and packages.  There are a few useful\nlittle pieces that didn't really fit in anyplace else.\n"
                },
                {
                    "name": "What Thread Am I In?",
                    "content": "The \"threads->self()\" class method provides your program with a way to get an object\nrepresenting the thread it's currently in.  You can use this object in the same way as the\nones returned from thread creation.\n"
                },
                {
                    "name": "Thread IDs",
                    "content": "\"tid()\" is a thread object method that returns the thread ID of the thread the object\nrepresents.  Thread IDs are integers, with the main thread in a program being 0.  Currently\nPerl assigns a unique TID to every thread ever created in your program, assigning the first\nthread to be created a TID of 1, and increasing the TID by 1 for each new thread that's\ncreated.  When used as a class method, \"threads->tid()\" can be used by a thread to get its\nown TID.\n"
                },
                {
                    "name": "Are These Threads The Same?",
                    "content": "The \"equal()\" method takes two thread objects and returns true if the objects represent the\nsame thread, and false if they don't.\n\nThread objects also have an overloaded \"==\" comparison so that you can do comparison on them\nas you would with normal objects.\n"
                },
                {
                    "name": "What Threads Are Running?",
                    "content": "\"threads->list()\" returns a list of thread objects, one for each thread that's currently\nrunning and not detached.  Handy for a number of things, including cleaning up at the end of\nyour program (from the main Perl thread, of course):\n\n# Loop through all the threads\nforeach my $thr (threads->list()) {\n$thr->join();\n}\n\nIf some threads have not finished running when the main Perl thread ends, Perl will warn you\nabout it and die, since it is impossible for Perl to clean up itself while other threads are\nrunning.\n\nNOTE:  The main Perl thread (thread 0) is in a detached state, and so does not appear in the\nlist returned by \"threads->list()\".\n"
                },
                {
                    "name": "A Complete Example",
                    "content": "Confused yet? It's time for an example program to show some of the things we've covered.\nThis program finds prime numbers using threads.\n\n1 #!/usr/bin/perl\n2 # prime-pthread, courtesy of Tom Christiansen\n3\n4 use strict;\n5 use warnings;\n6\n7 use threads;\n8 use Thread::Queue;\n9\n10 sub checknum {\n11     my ($upstream, $curprime) = @;\n12     my $kid;\n13     my $downstream = Thread::Queue->new();\n14     while (my $num = $upstream->dequeue()) {\n15         next unless ($num % $curprime);\n16         if ($kid) {\n17             $downstream->enqueue($num);\n18         } else {\n19             print(\"Found prime: $num\\n\");\n20             $kid = threads->create(\\&checknum, $downstream, $num);\n21             if (! $kid) {\n22                 warn(\"Sorry.  Ran out of threads.\\n\");\n23                 last;\n24             }\n25         }\n26     }\n27     if ($kid) {\n28         $downstream->enqueue(undef);\n29         $kid->join();\n30     }\n31 }\n32\n33 my $stream = Thread::Queue->new(3..1000, undef);\n34 checknum($stream, 2);\n\nThis program uses the pipeline model to generate prime numbers.  Each thread in the pipeline\nhas an input queue that feeds numbers to be checked, a prime number that it's responsible\nfor, and an output queue into which it funnels numbers that have failed the check.  If the\nthread has a number that's failed its check and there's no child thread, then the thread must\nhave found a new prime number.  In that case, a new child thread is created for that prime\nand stuck on the end of the pipeline.\n\nThis probably sounds a bit more confusing than it really is, so let's go through this program\npiece by piece and see what it does.  (For those of you who might be trying to remember\nexactly what a prime number is, it's a number that's only evenly divisible by itself and 1.)\n\nThe bulk of the work is done by the \"checknum()\" subroutine, which takes a reference to its\ninput queue and a prime number that it's responsible for.  After pulling in the input queue\nand the prime that the subroutine is checking (line 11), we create a new queue (line 13) and\nreserve a scalar for the thread that we're likely to create later (line 12).\n\nThe while loop from line 14 to line 26 grabs a scalar off the input queue and checks against\nthe prime this thread is responsible for.  Line 15 checks to see if there's a remainder when\nwe divide the number to be checked by our prime.  If there is one, the number must not be\nevenly divisible by our prime, so we need to either pass it on to the next thread if we've\ncreated one (line 17) or create a new thread if we haven't.\n\nThe new thread creation is line 20.  We pass on to it a reference to the queue we've created,\nand the prime number we've found.  In lines 21 through 24, we check to make sure that our new\nthread got created, and if not, we stop checking any remaining numbers in the queue.\n\nFinally, once the loop terminates (because we got a 0 or \"undef\" in the queue, which serves\nas a note to terminate), we pass on the notice to our child, and wait for it to exit if we've\ncreated a child (lines 27 and 30).\n\nMeanwhile, back in the main thread, we first create a queue (line 33) and queue up all the\nnumbers from 3 to 1000 for checking, plus a termination notice.  Then all we have to do to\nget the ball rolling is pass the queue and the first prime to the \"checknum()\" subroutine\n(line 34).\n\nThat's how it works.  It's pretty simple; as with many Perl programs, the explanation is much\nlonger than the program.\n"
                },
                {
                    "name": "Different implementations of threads",
                    "content": "Some background on thread implementations from the operating system viewpoint.  There are\nthree basic categories of threads: user-mode threads, kernel threads, and multiprocessor\nkernel threads.\n\nUser-mode threads are threads that live entirely within a program and its libraries.  In this\nmodel, the OS knows nothing about threads.  As far as it's concerned, your process is just a\nprocess.\n\nThis is the easiest way to implement threads, and the way most OSes start.  The big\ndisadvantage is that, since the OS knows nothing about threads, if one thread blocks they all\ndo.  Typical blocking activities include most system calls, most I/O, and things like\n\"sleep()\".\n\nKernel threads are the next step in thread evolution.  The OS knows about kernel threads, and\nmakes allowances for them.  The main difference between a kernel thread and a user-mode\nthread is blocking.  With kernel threads, things that block a single thread don't block other\nthreads.  This is not the case with user-mode threads, where the kernel blocks at the process\nlevel and not the thread level.\n\nThis is a big step forward, and can give a threaded program quite a performance boost over\nnon-threaded programs.  Threads that block performing I/O, for example, won't block threads\nthat are doing other things.  Each process still has only one thread running at once, though,\nregardless of how many CPUs a system might have.\n\nSince kernel threading can interrupt a thread at any time, they will uncover some of the\nimplicit locking assumptions you may make in your program.  For example, something as simple\nas \"$x = $x + 2\" can behave unpredictably with kernel threads if $x is visible to other\nthreads, as another thread may have changed $x between the time it was fetched on the right\nhand side and the time the new value is stored.\n\nMultiprocessor kernel threads are the final step in thread support.  With multiprocessor\nkernel threads on a machine with multiple CPUs, the OS may schedule two or more threads to\nrun simultaneously on different CPUs.\n\nThis can give a serious performance boost to your threaded program, since more than one\nthread will be executing at the same time.  As a tradeoff, though, any of those nagging\nsynchronization issues that might not have shown with basic kernel threads will appear with a\nvengeance.\n\nIn addition to the different levels of OS involvement in threads, different OSes (and\ndifferent thread implementations for a particular OS) allocate CPU cycles to threads in\ndifferent ways.\n\nCooperative multitasking systems have running threads give up control if one of two things\nhappen.  If a thread calls a yield function, it gives up control.  It also gives up control\nif the thread does something that would cause it to block, such as perform I/O.  In a\ncooperative multitasking implementation, one thread can starve all the others for CPU time if\nit so chooses.\n\nPreemptive multitasking systems interrupt threads at regular intervals while the system\ndecides which thread should run next.  In a preemptive multitasking system, one thread\nusually won't monopolize the CPU.\n\nOn some systems, there can be cooperative and preemptive threads running simultaneously.\n(Threads running with realtime priorities often behave cooperatively, for example, while\nthreads running at normal priorities behave preemptively.)\n\nMost modern operating systems support preemptive multitasking nowadays.\n"
                },
                {
                    "name": "Performance considerations",
                    "content": "The main thing to bear in mind when comparing Perl's ithreads to other threading models is\nthe fact that for each new thread created, a complete copy of all the variables and data of\nthe parent thread has to be taken. Thus, thread creation can be quite expensive, both in\nterms of memory usage and time spent in creation. The ideal way to reduce these costs is to\nhave a relatively short number of long-lived threads, all created fairly early on (before the\nbase thread has accumulated too much data). Of course, this may not always be possible, so\ncompromises have to be made. However, after a thread has been created, its performance and\nextra memory usage should be little different than ordinary code.\n\nAlso note that under the current implementation, shared variables use a little more memory\nand are a little slower than ordinary variables.\n"
                },
                {
                    "name": "Process-scope Changes",
                    "content": "Note that while threads themselves are separate execution threads and Perl data is thread-\nprivate unless explicitly shared, the threads can affect process-scope state, affecting all\nthe threads.\n\nThe most common example of this is changing the current working directory using \"chdir()\".\nOne thread calls \"chdir()\", and the working directory of all the threads changes.\n\nEven more drastic example of a process-scope change is \"chroot()\": the root directory of all\nthe threads changes, and no thread can undo it (as opposed to \"chdir()\").\n\nFurther examples of process-scope changes include \"umask()\" and changing uids and gids.\n\nThinking of mixing \"fork()\" and threads?  Please lie down and wait until the feeling passes.\nBe aware that the semantics of \"fork()\" vary between platforms.  For example, some Unix\nsystems copy all the current threads into the child process, while others only copy the\nthread that called \"fork()\". You have been warned!\n\nSimilarly, mixing signals and threads may be problematic.  Implementations are platform-\ndependent, and even the POSIX semantics may not be what you expect (and Perl doesn't even\ngive you the full POSIX API).  For example, there is no way to guarantee that a signal sent\nto a multi-threaded Perl application will get intercepted by any particular thread.\n(However, a recently added feature does provide the capability to send signals between\nthreads.  See \"THREAD SIGNALLING\" in threads for more details.)\n"
                },
                {
                    "name": "Thread-Safety of System Libraries",
                    "content": "Whether various library calls are thread-safe is outside the control of Perl.  Calls often\nsuffering from not being thread-safe include: \"localtime()\", \"gmtime()\",  functions fetching\nuser, group and network information (such as \"getgrent()\", \"gethostent()\", \"getnetent()\" and\nso on), \"readdir()\", \"rand()\", and \"srand()\". In general, calls that depend on some global\nexternal state.\n\nIf the system Perl is compiled in has thread-safe variants of such calls, they will be used.\nBeyond that, Perl is at the mercy of the thread-safety or -unsafety of the calls.  Please\nconsult your C library call documentation.\n\nOn some platforms the thread-safe library interfaces may fail if the result buffer is too\nsmall (for example the user group databases may be rather large, and the reentrant interfaces\nmay have to carry around a full snapshot of those databases).  Perl will start with a small\nbuffer, but keep retrying and growing the result buffer until the result fits.  If this\nlimitless growing sounds bad for security or memory consumption reasons you can recompile\nPerl with \"PERLREENTRANTMAXSIZE\" defined to the maximum number of bytes you will allow.\n"
                }
            ]
        },
        "Conclusion": {
            "content": "A complete thread tutorial could fill a book (and has, many times), but with what we've\ncovered in this introduction, you should be well on your way to becoming a threaded Perl\nexpert.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "Annotated POD for threads:\n<https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&field=Module&name=threads>\n\nLatest version of threads on CPAN: <https://metacpan.org/pod/threads>\n\nAnnotated POD for threads::shared:\n<https://web.archive.org/web/20171028020148/http://annocpan.org/?mode=search&field=Module&name=threads%3A%3Ashared>\n\nLatest version of threads::shared on CPAN: <https://metacpan.org/pod/threads::shared>\n\nPerl threads mailing list: <https://lists.perl.org/list/ithreads.html>\n",
            "subsections": []
        },
        "Bibliography": {
            "content": "Here's a short bibliography courtesy of Jürgen Christoffel:\n",
            "subsections": [
                {
                    "name": "Introductory Texts",
                    "content": "Birrell, Andrew D. An Introduction to Programming with Threads. Digital Equipment\nCorporation, 1989, DEC-SRC Research Report #35 online as\n<https://www.hpl.hp.com/techreports/Compaq-DEC/SRC-RR-35.pdf> (highly recommended)\n\nRobbins, Kay. A., and Steven Robbins. Practical Unix Programming: A Guide to Concurrency,\nCommunication, and Multithreading. Prentice-Hall, 1996.\n\nLewis, Bill, and Daniel J. Berg. Multithreaded Programming with Pthreads. Prentice Hall,\n1997, ISBN 0-13-443698-9 (a well-written introduction to threads).\n\nNelson, Greg (editor). Systems Programming with Modula-3.  Prentice Hall, 1991, ISBN\n0-13-590464-1.\n\nNichols, Bradford, Dick Buttlar, and Jacqueline Proulx Farrell.  Pthreads Programming.\nO'Reilly & Associates, 1996, ISBN 156592-115-1 (covers POSIX threads).\n"
                },
                {
                    "name": "OS-Related References",
                    "content": "Boykin, Joseph, David Kirschen, Alan Langerman, and Susan LoVerso. Programming under Mach.\nAddison-Wesley, 1994, ISBN 0-201-52739-1.\n\nTanenbaum, Andrew S. Distributed Operating Systems. Prentice Hall, 1995, ISBN 0-13-219908-4\n(great textbook).\n\nSilberschatz, Abraham, and Peter B. Galvin. Operating System Concepts, 4th ed. Addison-\nWesley, 1995, ISBN 0-201-59292-4\n"
                },
                {
                    "name": "Other References",
                    "content": "Arnold, Ken and James Gosling. The Java Programming Language, 2nd ed. Addison-Wesley, 1998,\nISBN 0-201-31006-6.\n\ncomp.programming.threads FAQ, <http://www.serpentine.com/~bos/threads-faq/>\n\nLe Sergent, T. and B. Berthomieu. \"Incremental MultiThreaded Garbage Collection on Virtually\nShared Memory Architectures\" in Memory Management: Proc. of the International Workshop IWMM\n92, St. Malo, France, September 1992, Yves Bekkers and Jacques Cohen, eds. Springer, 1992,\nISBN 3540-55940-X (real-life thread applications).\n\nArtur Bergman, \"Where Wizards Fear To Tread\", June 11, 2002,\n<http://www.perl.com/pub/a/2002/06/11/threads.html>\n"
                }
            ]
        },
        "Acknowledgements": {
            "content": "Thanks (in no particular order) to Chaim Frenkel, Steve Fink, Gurusamy Sarathy, Ilya\nZakharevich, Benjamin Sugars, Jürgen Christoffel, Joshua Pritikin, and Alan Burlison, for\ntheir help in reality-checking and polishing this article.  Big thanks to Tom Christiansen\nfor his rewrite of the prime number generator.\n",
            "subsections": []
        },
        "AUTHOR": {
            "content": "Dan Sugalski <dan@sidhe.org>\n\nSlightly modified by Arthur Bergman to fit the new thread model/module.\n\nReworked slightly by Jörg Walter <jwalt@cpan.org> to be more concise about thread-safety of\nPerl code.\n\nRearranged slightly by Elizabeth Mattijsen <liz@dijkmat.nl> to put less emphasis on yield().\n",
            "subsections": []
        },
        "Copyrights": {
            "content": "The original version of this article originally appeared in The Perl Journal #10, and is\ncopyright 1998 The Perl Journal. It appears courtesy of Jon Orwant and The Perl Journal.\nThis document may be distributed under the same terms as Perl itself.\n\n\n\nperl v5.34.0                                 2025-07-25                                PERLTHRTUT(1)",
            "subsections": []
        }
    },
    "summary": "perlthrtut - Tutorial on threads in Perl",
    "flags": [],
    "examples": [],
    "see_also": []
}