词条 | Thread (computing) |
释义 |
In computer science, a thread of execution is the smallest sequence of programmed instructions that can be managed independently by a scheduler, which is typically a part of the operating system.[1] The implementation of threads and processes differs between operating systems, but in most cases a thread is a component of a process. Multiple threads can exist within one process, executing concurrently and sharing resources such as memory, while different processes do not share these resources. In particular, the threads of a process share its executable code and the values of its dynamically allocated variables and non-thread-local global variables at any given time. Single vs multiprocessor systemsSystems with a single processor generally implement multithreading by time slicing: the central processing unit (CPU) switches between different software threads. This context switching generally happens very often and rapidly enough that users perceive the threads or tasks as running in parallel. On a multiprocessor or multi-core system, multiple threads can execute in parallel, with every processor or core executing a separate thread simultaneously; on a processor or core with hardware threads, separate software threads can also be executed concurrently by separate hardware threads. HistoryThreads made an early appearance under the name of "tasks" in OS/360 Multiprogramming with a Variable Number of Tasks (MVT) in 1967. Saltzer (1966) credits Victor A. Vyssotsky with the term "thread".[2] The process schedulers of many modern operating systems directly support both time-sliced and multiprocessor threading, and the operating system kernel allows programmers to manipulate threads by exposing required functionality through the system-call interface. Some threading implementations are called kernel threads, whereas light-weight processes (LWP) are a specific type of kernel thread that share the same state and information. Furthermore, programs can have user-space threads when threading with timers, signals, or other methods to interrupt their own execution, performing a sort of ad hoc time-slicing. Threads vs. processesThreads differ from traditional multitasking operating system processes in that:
Systems such as Windows NT and OS/2 are said to have cheap threads and expensive processes; in other operating systems there is not so great a difference except the cost of an address space switch which on some architectures (notably x86) results in a translation lookaside buffer (TLB) flush. Single threadingIn computer programming, single-threading is the processing of one command at a time.[3] The opposite of single-threading is multithreading.[4] In the formal analysis of the variables' semantics and process state the term single threading can be used differently to mean "backtracking within a single thread", which is common in the functional programming community.[5] MultithreadingMultithreading 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 enable parallel execution on a multiprocessing system. Multithreaded applications have the following advantages:
Multithreading has the following drawbacks:
SchedulingOperating systems schedule threads either preemptively or cooperatively. On multi-user operating systems, preemptive multithreading is the more widely used approach for its finer grained control over execution time via context switching. However, preemptive scheduling may context switch threads at moments unanticipated by programmers therefore causing lock convoy, priority inversion, or other side-effects. In contrast, cooperative multithreading relies on threads to relinquish control of execution thus ensuring that threads run to completion . This can create problems if a cooperatively multitasked thread blocks by waiting on a resource or if it starves 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 for hardware threads, although threads were still used on such computers because switching between threads was generally still quicker than full-process context switches. In 2002, Intel added support for simultaneous multithreading to the Pentium 4 processor, under the name hyper-threading; in 2005, they introduced the dual-core Pentium D processor and AMD introduced the dual-core Athlon 64 X2 processor. Processors in embedded systems, which have higher requirements for real-time behaviors, might support multithreading by decreasing the thread-switch time, perhaps by allocating a dedicated register file for each thread instead of saving/restoring a common register file. {{Anchor|KERNEL}}Processes, kernel threads, user threads, and fibers{{Main|Process (computing)|Fiber (computer science)}}Scheduling can be done at the kernel level or user level, and multitasking can be done preemptively or cooperatively. This yields a variety of related concepts. At the kernel level, a process contains one or more kernel 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 a runtime system can itself schedule multiple threads of execution. If these do not share data, as in Erlang, they are usually analogously called processes,[7] while if they share data they are usually called (user) threads, particularly if preemptively scheduled. Cooperatively scheduled user threads are known as fibers; 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 term "light-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 own resources allocated by the operating system. Resources include memory (for both code and data), file handles, sockets, device handles, windows, and a process control block. Processes are isolated by process 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 – see interprocess 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 of context switching, due to issues such as cache flushing.{{efn|1=Process switching changes virtual memory addressing, causing invalidation and thus flushing of an untagged translation lookaside buffer, notably on x86.}} A kernel 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 process scheduler is preemptive. Kernel threads do not own resources except for a stack, a copy of the registers including the program counter, and thread-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 thread to each logical core in a system (because each processor splits itself up into multiple logical cores if it supports multithreading, or only supports one logical core per physical core if it does not), and can swap out threads that get blocked. However, kernel threads take much longer than user threads to be swapped. Threads are sometimes implemented in userspace libraries, thus called user 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 from multi-processor machines (M:N model). In this article the term "thread" (without kernel or user qualifier) defaults to referring to kernel threads. User threads as implemented by virtual machines are also called green threads. User threads are generally fast to create and manage, but cannot take advantage of multithreading or multiprocessing, and will get blocked if all of their associated kernel threads get blocked even if there are some user threads that are ready to run. Fibers are an even lighter unit of scheduling which are cooperatively scheduled: a running fiber must explicitly "yield" to allow another fiber to run, which makes their implementation much easier than kernel or user 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). Parallel programming environments such as OpenMP typically implement their tasks through fibers. Closely related to fibers are coroutines, with the distinction being that coroutines are a language-level construct, while fibers are a system-level construct. Thread and fiber issuesConcurrency and data structuresThreads in the same process share the same address space. This allows concurrently running code to couple tightly and conveniently exchange data without the overhead or complexity of an IPC. When shared between threads, however, even simple data structures become prone to race 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, threading application programming interfaces (APIs) offer synchronization primitives such as mutexes to lock 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 a spinlock. Both of these may sap performance and force processors in symmetric multiprocessing (SMP) systems to contend for the memory bus, especially if the granularity of the locking is fine. {{quotation|Although threads seem to be a small step from sequential computation, in fact, they represent a huge step. They discard the most essential and appealing properties of sequential computation: understandability, predictability, and determinism. Threads, as a model of computation, are wildly non-deterministic, and the job of the programmer becomes one of pruning that nondeterminism. | The Problem with Threads, Edward A. Lee, UC Berkeley, 2006[8]}}I/O and schedulingUser thread or fiber implementations are typically entirely in userspace. As a result, context switching between user threads or fibers 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) or fibers 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 is providing an I/O API that implements a synchronous interface 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. SunOS 4.x implemented light-weight processes or LWPs. NetBSD 2.x+, and DragonFly 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.[9] 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. The use of kernel threads simplifies user code by moving some of the most complex aspects of threading into the kernel. The program does not need to schedule threads or explicitly yield the processor. User code can be written in a familiar procedural style, including calls to blocking APIs, without starving other threads. However, kernel threading may force a context switch between threads at any time, and thus expose race hazards and concurrency bugs that would otherwise lie latent. On SMP systems, this is further exacerbated because kernel threads may literally execute on separate processors in parallel. Models1:1 (kernel-level threading)Threads created by the user in a 1:1 correspondence with schedulable entities in the kernel[10] are the simplest possible threading implementation. OS/2 and Win32 used this approach from the start, while on Linux the usual C library implements this approach (via the NPTL or older LinuxThreads). This approach is also used by Solaris, NetBSD, FreeBSD, macOS, and iOS. N:1 (user-level threading)An N:1 model implies that all application-level threads map to one kernel-level scheduled entity;[10] 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 on multithreaded processors or multi-processor computers: there is never more than one thread being scheduled at the same time.[10] 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. The GNU Portable Threads uses User-level threading, as does State Threads. M:N (hybrid threading)M:N maps some M number of application threads onto some N number of kernel entities,[10] 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. 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 of priority inversion, as well as suboptimal scheduling without extensive (and expensive) coordination between the userland scheduler and the kernel scheduler. Hybrid implementation examples
Fiber implementation examplesFibers can be implemented without operating system support, although some operating systems or libraries provide explicit support for them.
Programming language supportIBM PL/I(F) included support for multithreading (called multitasking) in the late 1960s, and this was continued in the Optimizing Compiler and later versions. The IBM Enterprise PL/I compiler introduced a new model "thread" API. Neither version was part of the PL/I standard. Many programming languages support threading in some capacity. Many implementations of C and C++ support threading, and provide access to the native threading APIs of the operating system. Some higher level (and usually cross-platform) programming languages, such as Java, Python, and .NET Framework languages, expose threading to developers while abstracting the platform specific differences in threading implementations in the runtime. Several other programming languages and language extensions also try to abstract the concept of concurrency and threading from the developer fully (Cilk, OpenMP, Message Passing Interface (MPI)). Some languages are designed for sequential parallelism instead (especially using GPUs), without requiring concurrency or threads (Ateji PX, CUDA). A few interpreted programming languages have implementations (e.g., Ruby MRI for Ruby, CPython for Python) which support threading and concurrency but not parallel execution of threads, due to a global interpreter lock (GIL). The GIL is a mutual exclusion lock held by the interpreter that can prevent the interpreter from simultaneously interpreting the applications code on two or more threads at once, which effectively limits the parallelism on multiple core systems. This limits performance mostly for processor-bound threads, which require the processor, and not much for I/O-bound or network-bound ones. Other implementations of interpreted programming languages, such as Tcl using the Thread extension, avoid the GIL limit by using an Apartment model where data and code must be explicitly "shared" between threads. In Tcl each thread has one or more interpreters. Event-driven programming hardware description languages such as Verilog have a different threading model that supports extremely large numbers of threads (for modeling hardware). Practical multithreadingA standardized interface for thread implementation is POSIX Threads (Pthreads), which is a set of C-function library calls. OS vendors are free to implement the interface as desired, but the application developer should be able to use the same interface across multiple platforms. Most Unix platforms including Linux support Pthreads. Microsoft Windows has its own set of thread functions in the process.h interface for multithreading, like beginthread. Java provides yet another standardized interface over the host operating system using the Java concurrency library java.util.concurrent. Multithreading libraries 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 synchronization functions which make it possible to implement race condition-error free multithreading functions using mutexes, condition variables, critical sections, semaphores, monitors and other synchronization primitives. Another paradigm of thread usage is that of thread 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. For example, frameworks like Grand Central Dispatch and Threading Building Blocks. In programming models such as CUDA designed for data parallel computation, an array of threads run the same code in parallel using only its ID to find its data in memory. In essence, the application must be designed so that each thread performs the same operation on different segments of memory so that they can operate in parallel and use the GPU architecture. See also{{Portal|Computer programming|Computing}}{{Div col|colwidth=20em}}
Notes{{notelist}}References1. ^{{cite journal|last1= Lamport|first1= Leslie|authorlink= Leslie Lamport|title= How to Make a Multiprocessor Computer That Correctly Executes Multiprocess Programs|journal= IEEE Transactions on Computers|volume= C-28|number= 9|pages= 690–691|date= September 1979|url= http://research.microsoft.com/en-us/um/people/lamport/pubs/multi.pdf|doi=10.1109/tc.1979.1675439}} {{refbegin|colwidth=30em}}{{refend}}2. ^Traffic Control in a Multiplexed Computer System, Jerome Howard Saltzer, Doctor of Science thesis, 1966, see footnote on page 20. 3. ^{{Cite book|author=Raúl Menéndez|author2=Doug Lowe |title=Murach's CICS for the COBOL Programmer|page=512|publisher=Mike Murach & Associates|date=2001|isbn=978-1-890774-09-7|url=https://books.google.com/books?id=j1t1u_UniU0C&q=%22single+threading%22&dq=%22single+threading%22}} 4. ^{{Cite book|author=Stephen R. G. Fraser|title=Pro Visual C++/CLI and the .NET 3.5 Platform|page=780|publisher=Apress|isbn=978-1-4302-1053-5|url=https://books.google.com/?id=MTJIdMoaY1gC&dq=%22single+threading%22|date=2008-12-11}} 5. ^{{Cite book|author=Peter William O'Hearn|author2=R. D. Tennent |title=ALGOL-like languages|volume=2|publisher=Birkhäuser Verlag|date=1997|page=157|isbn=978-0-8176-3937-2|url=https://books.google.com/books?id=btp58ihqgccC&pg=PA157}} 6. ^Single-Threading: Back to the Future? Sergey Ignatchenko, Overload #97 7. ^{{cite web|title=Erlang: 3.1 Processes|url=http://www.erlang.org/doc/getting_started/conc_prog.html}} 8. ^"The Problem with Threads", Edward A. Lee, UC Berkeley, January 10, 2006, Technical Report No. UCB/EECS-2006-1 9. ^{{cite web|url=http://www.sun.com/software/whitepapers/solaris9/multithread.pdf|title=Multithreading in the Solaris Operating Environment|year=2002|archiveurl=https://web.archive.org/web/20090226174929/http://www.sun.com/software/whitepapers/solaris9/multithread.pdf |archivedate=February 26, 2009}} 10. ^1 2 3 {{cite book|last=Gagne|first=Abraham Silberschatz, Peter Baer Galvin, Greg|title=Operating system concepts|year=2013|publisher=Wiley|location=Hoboken, N.J.|isbn=9781118063330|pages=170–171|edition=9th}} 11. ^{{cite web|url=https://os.itec.kit.edu/downloads/sa_2010_rittinghaus-marc_syscall-aggregation.pdf|title=System Call Aggregation for a Hybrid Thread Model|author=Marc Rittinghaus|date=23 December 2010|page=10}} 12. ^{{cite web|url=https://docs.microsoft.com/en-us/windows/desktop/ProcThread/user-mode-scheduling|title=User-Mode Scheduling|website=Microsoft Docs|date=30 May 2018}} 13. ^CreateFiber, MSDN Further reading{{Div col|colwidth=30em}}
External links{{Wikiversity|at=Operating Systems/Process and Thread|Processes and Threads}}
2 : Concurrent computing|Threads (computing) |
随便看 |
|
开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。