Incomputer science, athread ofexecution is the smallest sequence of programmed instructions that can be managed independently by ascheduler, which is typically a part of theoperating system.[1] In many cases, a thread is a component of aprocess.
The multiple threads of a given process may be executedconcurrently (via multithreading capabilities), sharing resources such asmemory, while different processes do not share these resources. In particular, the threads of a process share its executable code and the values of itsdynamically allocated variables and non-thread-localglobal variables at any given time.
The implementation of threads andprocesses differs between operating systems.[2][page needed]
![]() | This sectionneeds expansion. You can help byadding to it.(February 2021) |
Threads made an early appearance under the name of "tasks" in IBM's batch processing operating system, OS/360, in 1967. It provided users with three available configurations of theOS/360 control system, of whichmultiprogramming with a variable number of tasks (MVT) was one. Saltzer (1966) creditsVictor A. Vyssotsky with the term "thread".[3]
The use of threads in software applications became more common in the early 2000s as CPUs began to utilize multiple cores. Applications wishing to take advantage of multiple cores for performance advantages were required to employ concurrency to utilize the multiple cores.[4]
Scheduling can be done at the kernel level or user level, and multitasking can be donepreemptively orcooperatively. This yields a variety of related concepts.
At the kernel level, aprocess contains one or morekernel threads, which share the process's resources, such as memory and file handles – a process is a unit of resources, while a thread is a unit of scheduling and execution. Kernel scheduling is typically uniformly done preemptively or, less commonly, cooperatively. At the user level a process such as aruntime system can itself schedule multiple threads of execution. If these do not share data, as inErlang, they are usually analogously called processes,[5] while if they share data they are usually called(user) threads, particularly if preemptively scheduled. Cooperatively scheduled user threads are known asfibers; different processes may schedule user threads differently. User threads may be executed by kernel threads in various ways (one-to-one, many-to-one, many-to-many). The termlight-weight process variously refers to user threads or to kernel mechanisms for scheduling user threads onto kernel threads.
A process is a heavyweight unit of kernel scheduling, as creating, destroying, and switching processes is relatively expensive. Processes ownresources allocated by the operating system. Resources include memory (for both code and data),file handles, sockets, device handles, windows, and aprocess control block. Processes areisolated byprocess isolation, and do not share address spaces or file resources except through explicit methods such as inheriting file handles or shared memory segments, or mapping the same file in a shared way – seeInterprocess communication. Creating or destroying a process is relatively expensive, as resources must be acquired or released. Processes are typically preemptively multitasked, and process switching is relatively expensive, beyond basic cost ofcontext switching, due to issues such as cache flushing (in particular, process switching changes virtual memory addressing, causing invalidation and thus flushing of an untaggedtranslation lookaside buffer (TLB), notably onx86).
Akernel thread is a lightweight unit of kernel scheduling. At least one kernel thread exists within each process. If multiple kernel threads exist within a process, then they share the same memory and file resources. Kernel threads are preemptively multitasked if the operating system's processscheduler is preemptive. Kernel threads do not own resources except for astack, a copy of theregisters including theprogram counter, andthread-local storage (if any), and are thus relatively cheap to create and destroy. Thread switching is also relatively cheap: it requires a context switch (saving and restoring registers and stack pointer), but does not change virtual memory and is thus cache-friendly (leaving TLB valid). The kernel can assign one or more software threads to each core in a CPU (it being able to assign itself multiple software threads depending on its support for multithreading), and can swap out threads that get blocked. However, kernel threads take much longer than user threads to be swapped.
Threads are sometimes implemented inuserspace libraries, thus calleduser threads. The kernel is unaware of them, so they are managed and scheduled in userspace. Some implementations base their user threads on top of several kernel threads, to benefit frommulti-processor machines (M:N model). User threads as implemented byvirtual machines are also calledgreen threads.
As user thread implementations are typically entirely in userspace, context switching between user threads within the same process is extremely efficient because it does not require any interaction with the kernel at all: a context switch can be performed by locally saving the CPU registers used by the currently executing user thread or fiber and then loading the registers required by the user thread or fiber to be executed. Since scheduling occurs in userspace, the scheduling policy can be more easily tailored to the requirements of the program's workload.
However, the use of blocking system calls in user threads (as opposed to kernel threads) can be problematic. If a user thread or a fiber performs a system call that blocks, the other user threads and fibers in the process are unable to run until the system call returns. A typical example of this problem is when performing I/O: most programs are written to perform I/O synchronously. When an I/O operation is initiated, a system call is made, and does not return until the I/O operation has been completed. In the intervening period, the entire process is "blocked" by the kernel and cannot run, which starves other user threads and fibers in the same process from executing.
A common solution to this problem (used, in particular, by many green threads implementations) is providing an I/OAPI that implements an interface that blocks the calling thread, rather than the entire process, by using non-blocking I/O internally, and scheduling another user thread or fiber while the I/O operation is in progress. Similar solutions can be provided for other blocking system calls. Alternatively, the program can be written to avoid the use of synchronous I/O or other blocking system calls (in particular, using non-blocking I/O, including lambda continuations and/or async/await primitives[6]).
Fibers are an even lighter unit of scheduling which arecooperatively scheduled: a running fiber must explicitlyyield to allow another fiber to run, which makes their implementation much easier than kernel oruser threads. A fiber can be scheduled to run in any thread in the same process. This permits applications to gain performance improvements by managing scheduling themselves, instead of relying on the kernel scheduler (which may not be tuned for the application). Some research implementations of theOpenMP parallel programming model implement their tasks through fibers.[7][8] Closely related to fibers arecoroutines, with the distinction being that coroutines are a language-level construct, while fibers are a system-level construct.
Threads differ from traditionalmultitasking operating-systemprocesses in several ways:
Systems such asWindows NT andOS/2 are said to havecheap threads andexpensive processes; in other operating systems there is not so great a difference except in the cost of anaddress-space switch, which on some architectures (notablyx86) results in atranslation lookaside buffer (TLB) flush.
Advantages and disadvantages of threads vs processes include:
Operating systems schedule threads eitherpreemptively orcooperatively. Multi-user operating systems generally favorpreemptive multithreading for its finer-grained control over execution time viacontext switching. However, preemptive scheduling may context-switch threads at moments unanticipated by programmers, thus causinglock convoy,priority inversion, or other side-effects. In contrast,cooperative multithreading relies on threads to relinquish control of execution, thus ensuring that threadsrun to completion. This can cause problems if a cooperatively-multitasked threadblocks by waiting on a resource or if itstarves other threads by not yielding control of execution during intensive computation.
Until the early 2000s, most desktop computers had only one single-core CPU, with no support forhardware threads, although threads were still used on such computers because switching between threads was generally still quicker than full-processcontext switches. In 2002,Intel added support forsimultaneous multithreading to thePentium 4 processor, under the namehyper-threading; in 2005, they introduced the dual-corePentium D processor andAMD introduced the dual-coreAthlon 64 X2 processor.
Systems with a single processor generally implement multithreading bytime slicing: thecentral processing unit (CPU) switches between differentsoftware threads. Thiscontext switching usually occurs frequently enough that users perceive the threads or tasks as running in parallel (for popular server/desktop operating systems, maximum time slice of a thread, when other threads are waiting, is often limited to 100–200ms). On amultiprocessor ormulti-core system, multiple threads can execute inparallel, with every processor or core executing a separate thread simultaneously; on a processor or core withhardware threads, separate software threads can also be executed concurrently by separate hardware threads.
Threads created by the user in a 1:1 correspondence with schedulable entities in the kernel[9] are the simplest possible threading implementation.OS/2 andWin32 used this approach from the start, while onLinux theGNU C Library implements this approach (via theNPTL or olderLinuxThreads). This approach is also used bySolaris,NetBSD,FreeBSD,macOS, andiOS.
AnM:1 model implies that all application-level threads map to one kernel-level scheduled entity;[9] the kernel has no knowledge of the application threads. With this approach, context switching can be done very quickly and, in addition, it can be implemented even on simple kernels which do not support threading. One of the major drawbacks, however, is that it cannot benefit from the hardware acceleration onmultithreaded processors ormulti-processor computers: there is never more than one thread being scheduled at the same time.[9] For example: If one of the threads needs to execute an I/O request, the whole process is blocked and the threading advantage cannot be used. TheGNU Portable Threads uses User-level threading, as doesState Threads.
M:N maps someM number of application threads onto someN number of kernel entities,[9] or "virtual processors." This is a compromise between kernel-level ("1:1") and user-level ("N:1") threading. In general, "M:N" threading systems are more complex to implement than either kernel or user threads, because changes to both kernel and user-space code are required[clarification needed]. In the M:N implementation, the threading library is responsible for scheduling user threads on the available schedulable entities; this makes context switching of threads very fast, as it avoids system calls. However, this increases complexity and the likelihood ofpriority inversion, as well as suboptimal scheduling without extensive (and expensive) coordination between the userland scheduler and the kernel scheduler.
SunOS 4.x implementedlight-weight processes or LWPs.NetBSD 2.x+, andDragonFly BSD implement LWPs as kernel threads (1:1 model). SunOS 5.2 through SunOS 5.8 as well as NetBSD 2 to NetBSD 4 implemented a two level model, multiplexing one or more user level threads on each kernel thread (M:N model). SunOS 5.9 and later, as well as NetBSD 5 eliminated user threads support, returning to a 1:1 model.[10] FreeBSD 5 implemented M:N model. FreeBSD 6 supported both 1:1 and M:N, users could choose which one should be used with a given program using /etc/libmap.conf. Starting with FreeBSD 7, the 1:1 became the default. FreeBSD 8 no longer supports the M:N model.
Incomputer programming,single-threading is the processing of oneinstruction at a time.[11] In the formal analysis of the variables'semantics and process state, the termsingle threading can be used differently to mean "backtracking within a single thread", which is common in thefunctional programming community.[12]
Multithreading is mainly found in multitasking operating systems. Multithreading is a widespread programming and execution model that allows multiple threads to exist within the context of one process. These threads share the process's resources, but are able to execute independently. The threaded programming model provides developers with a useful abstraction of concurrent execution. Multithreading can also be applied to one process to enableparallel execution on amultiprocessing system.
Multithreading libraries tend to provide a function call to create a new thread, which takes a function as a parameter. A concurrent thread is then created which starts running the passed function and ends when the function returns. The thread libraries also offer data synchronization functions.
Threads in the same process share the same address space. This allows concurrently running code tocouple tightly and conveniently exchange data without the overhead or complexity of anIPC. When shared between threads, however, even simple data structures become prone torace conditions if they require more than one CPU instruction to update: two threads may end up attempting to update the data structure at the same time and find it unexpectedly changing underfoot. Bugs caused by race conditions can be very difficult to reproduce and isolate.
To prevent this, threadingapplication programming interfaces (APIs) offersynchronization primitives such asmutexes tolock data structures against concurrent access. On uniprocessor systems, a thread running into a locked mutex must sleep and hence trigger a context switch. On multi-processor systems, the thread may instead poll the mutex in aspinlock. Both of these may sap performance and force processors insymmetric multiprocessing (SMP) systems to contend for the memory bus, especially if thegranularity of the locking is too fine.
Other synchronization APIs includecondition variables,critical sections,semaphores, andmonitors.
A popular programming pattern involving threads is that ofthread pools where a set number of threads are created at startup that then wait for a task to be assigned. When a new task arrives, it wakes up, completes the task and goes back to waiting. This avoids the relatively expensive thread creation and destruction functions for every task performed and takes thread management out of the application developer's hand and leaves it to a library or the operating system that is better suited to optimize thread management.
Multithreaded applications have the following advantages vs single-threaded ones:
Multithreaded applications have the following drawbacks:
Many programming languages support threading in some capacity.
{{cite AV media}}
: CS1 maint: bot: original URL status unknown (link)