In
computer programming
Computer programming or coding is the composition of sequences of instructions, called computer program, programs, that computers can follow to perform tasks. It involves designing and implementing algorithms, step-by-step specifications of proc ...
, a green thread is a
thread that is scheduled by a
runtime library
A runtime library is a library that provides access to the runtime environment that is available to a computer program tailored to the host platform. A runtime environment implements the execution model as required for a development environme ...
or
virtual machine
In computing, a virtual machine (VM) is the virtualization or emulator, emulation of a computer system. Virtual machines are based on computer architectures and provide the functionality of a physical computer. Their implementations may involve ...
(VM) instead of natively by the underlying
operating system
An operating system (OS) is system software that manages computer hardware and software resources, and provides common daemon (computing), services for computer programs.
Time-sharing operating systems scheduler (computing), schedule tasks for ...
(OS). Green threads emulate multithreaded environments without relying on any native OS abilities, and they are managed in
user space
A modern computer operating system usually uses virtual memory to provide separate address spaces or regions of a single address space, called user space and kernel space. This separation primarily provides memory protection and hardware prote ...
instead of
kernel space, enabling them to work in environments that do not have native thread support.
Etymology
Green threads refers to the name of the original thread
library
A library is a collection of Book, books, and possibly other Document, materials and Media (communication), media, that is accessible for use by its members and members of allied institutions. Libraries provide physical (hard copies) or electron ...
for
Java
Java is one of the Greater Sunda Islands in Indonesia. It is bordered by the Indian Ocean to the south and the Java Sea (a part of Pacific Ocean) to the north. With a population of 156.9 million people (including Madura) in mid 2024, proje ...
programming language (that was released in version
1.1 and then Green threads were abandoned in version
1.3 to native threads). It was designed by ''The Green Team'' at
Sun Microsystems
Sun Microsystems, Inc., often known as Sun for short, was an American technology company that existed from 1982 to 2010 which developed and sold computers, computer components, software, and information technology services. Sun contributed sig ...
.
History
Green threads were briefly available in Java between 1997 and 2000.
Green threads share a single operating system thread through co-operative concurrency and can therefore not achieve parallelism performance gains like operating system threads. The main benefit of coroutines and green threads is ease of implementation.
Performance
On a
multi-core processor
A multi-core processor (MCP) is a microprocessor on a single integrated circuit (IC) with two or more separate central processing units (CPUs), called ''cores'' to emphasize their multiplicity (for example, ''dual-core'' or ''quad-core''). Ea ...
, native thread implementations can automatically assign work to multiple processors, whereas green thread implementations normally cannot.
Green threads can be started much faster on some VMs. On uniprocessor computers, however, the most efficient model has not yet been clearly determined.
Benchmarks on computers running the
Linux kernel
The Linux kernel is a Free and open-source software, free and open source Unix-like kernel (operating system), kernel that is used in many computer systems worldwide. The kernel was created by Linus Torvalds in 1991 and was soon adopted as the k ...
version 2.2 (released in 1999) have shown that:
* Green threads significantly outperform Linux native threads on thread activation and
synchronization
Synchronization is the coordination of events to operate a system in unison. For example, the Conductor (music), conductor of an orchestra keeps the orchestra synchronized or ''in time''. Systems that operate with all parts in synchrony are sa ...
.
* Linux native threads have slightly better performance on
input/output
In computing, input/output (I/O, i/o, or informally io or IO) is the communication between an information processing system, such as a computer, and the outside world, such as another computer system, peripherals, or a human operator. Inputs a ...
(I/O) and
context switch
In computing, a context switch is the process of storing the state of a process or thread, so that it can be restored and resume execution at a later point, and then restoring a different, previously saved, state. This allows multiple processes ...
ing operations.
When a green thread executes a blocking system call, not only is that thread blocked, but all of the threads within the process are blocked. To avoid that problem, green threads must use
non-blocking I/O
In computer science, asynchronous I/O (also non-sequential I/O) is a form of input/output processing that permits other processing to continue before the I/O operation has finished. A name used for asynchronous I/O in the Windows API is '' over ...
or
asynchronous I/O
In computer science, asynchronous I/O (also non-sequential I/O) is a form of input/output processing that permits other processing to continue before the I/O operation has finished. A name used for asynchronous I/O in the Windows API is '' over ...
operations, although the increased complexity on the user side can be reduced if the
virtual machine
In computing, a virtual machine (VM) is the virtualization or emulator, emulation of a computer system. Virtual machines are based on computer architectures and provide the functionality of a physical computer. Their implementations may involve ...
implementing the green threads spawns specific I/O processes (hidden to the user) for each I/O operation.
There are also mechanisms which allow use of native threads and reduce the overhead of thread activation and synchronization:
*
Thread pool
In computer programming, a thread pool is a software design pattern for achieving concurrency of execution in a computer program. Often also called a replicated workers or worker-crew model, a thread pool maintains multiple threads waiting for ...
s reduce the cost of spawning a new thread by reusing a limited number of threads.
* Languages which use virtual machines and native threads can use
escape analysis to avoid synchronizing blocks of code when unneeded.
Green threads in the Java Virtual Machine
In
Java 1.1
The Java language has undergone several changes since JDK 1.0 as well as numerous additions of classes and packages to the standard library. Since J2SE 1.4, the evolution of the Java language has been governed by the Java Community P ...
, green threads were the only threading model used by the
Java virtual machine
A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally descr ...
(JVM), at least on
Solaris
Solaris is the Latin word for sun.
It may refer to:
Arts and entertainment Literature, television and film
* ''Solaris'' (novel), a 1961 science fiction novel by Stanisław Lem
** ''Solaris'' (1968 film), directed by Boris Nirenburg
** ''Sol ...
. As green threads have some limitations compared to native threads, subsequent Java versions dropped them in favor of native threads.
An exception to this is the
Squawk virtual machine, which is a mixture between an
operating system
An operating system (OS) is system software that manages computer hardware and software resources, and provides common daemon (computing), services for computer programs.
Time-sharing operating systems scheduler (computing), schedule tasks for ...
for low-power devices and a Java virtual machine. It uses green threads to minimize the use of
native code
In computer programming, machine code is computer program, computer code consisting of machine language instruction set architecture, instructions, which are used to control a computer's central processing unit (CPU). For conventional binary ...
, and to support migrating its isolates.
Kilim and Quasar
are open-source projects which implement green threads on later versions of the JVM by modifying the
Java bytecode
Java bytecode is the instruction set of the Java virtual machine (JVM), the language to which Java and other JVM-compatible source code is compiled. Each instruction is represented by a single byte, hence the name bytecode, making it a compact ...
produced by the Java compiler (Quasar also supports
Kotlin and
Clojure
Clojure (, like ''closure'') is a dynamic programming language, dynamic and functional programming, functional dialect (computing), dialect of the programming language Lisp (programming language), Lisp on the Java (software platform), Java platfo ...
).
Green threads in other languages
There are some other
programming language
A programming language is a system of notation for writing computer programs.
Programming languages are described in terms of their Syntax (programming languages), syntax (form) and semantics (computer science), semantics (meaning), usually def ...
s that implement equivalents of green threads instead of native threads. Examples:
*
Chicken
The chicken (''Gallus gallus domesticus'') is a domesticated subspecies of the red junglefowl (''Gallus gallus''), originally native to Southeast Asia. It was first domesticated around 8,000 years ago and is now one of the most common and w ...
Scheme uses lightweight user-level threads based on first-class continuations
*
Common Lisp
Common Lisp (CL) is a dialect of the Lisp programming language, published in American National Standards Institute (ANSI) standard document ''ANSI INCITS 226-1994 (S2018)'' (formerly ''X3.226-1994 (R1999)''). The Common Lisp HyperSpec, a hyperli ...
*
CPython
CPython is the reference implementation of the Python programming language. Written in C and Python, CPython is the default and most widely used implementation of the Python language.
CPython can be defined as both an interpreter and a comp ...
natively support
asynciosince Version 3.4, alternative implementations exist lik
greenleteventletan
gevent PyPy
*
Crystal
A crystal or crystalline solid is a solid material whose constituents (such as atoms, molecules, or ions) are arranged in a highly ordered microscopic structure, forming a crystal lattice that extends in all directions. In addition, macros ...
offers
fibers
Fiber (spelled fibre in British English; from ) is a natural or artificial substance that is significantly longer than it is wide. Fibers are often used in the manufacture of other materials. The strongest engineering materials often inco ...
*
D offers
fibers
Fiber (spelled fibre in British English; from ) is a natural or artificial substance that is significantly longer than it is wide. Fibers are often used in the manufacture of other materials. The strongest engineering materials often inco ...
, used for asynchronous I/O
*
Dyalog APL terms them ''threads''
*
Erlang
*
Go implements so calle
goroutinesref name="GoDogma">
*
Haskell
Haskell () is a general-purpose, statically typed, purely functional programming language with type inference and lazy evaluation. Designed for teaching, research, and industrial applications, Haskell pioneered several programming language ...
*
Julia uses green threads for it
Tasks
*
Limbo
The unofficial term Limbo (, or , referring to the edge of Hell) is the afterlife condition in medieval Catholic theology, of those who die in original sin without being assigned to the Hell of the Damned. However, it has become the gene ...
*
Lua use
coroutinesfor concurrency. Lua 5.2 also offers true C coroutine semantics through the function
an
Th
CoCoextension allows true C coroutine semantics for Lua 5.1.
*
Nim provides asynchronous I/O and coroutines
*
OCaml
OCaml ( , formerly Objective Caml) is a General-purpose programming language, general-purpose, High-level programming language, high-level, Comparison of multi-paradigm programming languages, multi-paradigm programming language which extends the ...
, since version 5.0, supports green threads through th
Domainslib.Taskmodule
*
occam, which prefers the term ''process'' instead of ''thread'' due to its origins in
communicating sequential processes
In computer science, communicating sequential processes (CSP) is a formal language for describing patterns of interaction in concurrent systems. It is a member of the family of mathematical theories of concurrency known as process algebras, or p ...
*
Perl
Perl is a high-level, general-purpose, interpreted, dynamic programming language. Though Perl is not officially an acronym, there are various backronyms in use, including "Practical Extraction and Reporting Language".
Perl was developed ...
supports green threads throug
coroutines*
PHP
PHP is a general-purpose scripting language geared towards web development. It was originally created by Danish-Canadian programmer Rasmus Lerdorf in 1993 and released in 1995. The PHP reference implementation is now produced by the PHP Group. ...
supports green threads throug
fibersan
*
Racket (native threads are also available through Places)
*
Ruby
Ruby is a pinkish-red-to-blood-red-colored gemstone, a variety of the mineral corundum ( aluminium oxide). Ruby is one of the most popular traditional jewelry gems and is very durable. Other varieties of gem-quality corundum are called sapph ...
before version 1.9
*
SML/NJ's implementation of
Concurrent ML
Concurrent ML (CML) is a multi-paradigm, general-purpose, high-level, functional programming language. It is a dialect of the programming language ML which is a concurrent extension of the Standard ML language, characterized by its ability ...
*
Smalltalk
Smalltalk is a purely object oriented programming language (OOP) that was originally created in the 1970s for educational use, specifically for constructionist learning, but later found use in business. It was created at Xerox PARC by Learni ...
(most dialects:
Squeak
Squeak is an object-oriented, class-based, and reflective programming language. It was derived from Smalltalk-80 by a group that included some of Smalltalk-80's original developers, initially at Apple Computer, then at Walt Disney Imaginee ...
, VisualWorks,
GNU Smalltalk
GNU Smalltalk is an implementation of the Smalltalk programming language by the GNU Project.
The implementation, unlike other Smalltalk environments, uses text files for program input and interprets the contents as Smalltalk code. In this way, G ...
, etc.)
*
Stackless Python supports either
preemptive multitasking
In computing, preemption is the act performed by an external scheduler — without assistance or cooperation from the task — of temporarily interrupting an executing task, with the intention of resuming it at a later time. This preemptive sc ...
or cooperative multitasking through microthreads (termed ''tasklets'').
*
Tcl
TCL or Tcl or TCLs may refer to:
Business
* TCL Technology, a Chinese consumer electronics and appliance company
** TCL Electronics, a subsidiary of TCL Technology
* Texas Collegiate League, a collegiate baseball league
* Trade Centre Limited ...
ha
coroutinesand an event loop
The
Erlang virtual machine has what might be called ''green processes'' – they are like operating system processes (they do not share state like threads do) but are implemented within the Erlang Run Time System (erts). These are sometimes termed ''green threads'', but have significant differences from standard green threads.
In the case of GHC Haskell, a context switch occurs at the first allocation after a configurable timeout. GHC threads are also potentially run on one or more OS threads during their lifetime (there is a many-to-many relationship between GHC threads and OS threads), allowing for parallelism on
symmetric multiprocessing
Symmetric multiprocessing or shared-memory multiprocessing (SMP) involves a multiprocessor computer hardware and software architecture where two or more identical processors are connected to a single, shared main memory, have full access to all ...
machines, while not creating more costly OS threads than needed to run on the available number of cores.
Most Smalltalk virtual machines do not count evaluation steps; however, the VM can still preempt the executing thread on external signals (such as expiring timers, or I/O becoming available). Usually
round-robin scheduling
Round-robin (RR) is one of the algorithms employed by process and network schedulers in computing. Guowang Miao, Jens Zander, Ki Won Sung, and Ben Slimane, Fundamentals of Mobile Data Networks, Cambridge University Press, , 2016.
As the term ...
is used so that a high-priority process that wakes up regularly will effectively implement
time-sharing preemption:
[(Delay forMilliseconds: 50) waitrepeat
">Delay forMilliseconds: 50) wait"> [(Delay forMilliseconds: 50) waitrepeat
forkAt: Processor highIOPriority
Other implementations, e.g., QKS Smalltalk, are always time-sharing. Unlike most green thread implementations, QKS also supports preventing priority inversion.
Differences to virtual threads in the Java Virtual Machine
Virtual thread, Virtual threads were introduced as a preview feature in Java 19 and stabilized in Java 21. Important differences between virtual threads and green threads are:
* Virtual threads coexist with existing (non-virtual) platform threads and thread pools.
* Virtual threads protect their abstraction:
** Unlike with green threads, sleeping on a virtual thread does not block the underlying carrier thread.
** Working with thread-local variables is deemphasized, and scoped values are suggested as a more lightweight replacement.
* Virtual threads can be cheaply suspended and resumed, making use of JVM support for the special
jdk.internal.vm.Continuation
class.
* Virtual threads handle blocking calls by transparently unmounting from the carrier thread where possible, otherwise compensating by increasing the number of platform threads.
See also
*
Async/await
In computer programming, the async/await pattern is a syntactic feature of many programming languages that allows an asynchronous, non-blocking function to be structured in a way similar to an ordinary synchronous function. It is semantically r ...
*
Light-weight process
In computer operating systems, a light-weight process (LWP) is a means of achieving multitasking. In the traditional meaning of the term, as used in Unix System V and Solaris, a LWP runs in user space on top of a single kernel thread and shar ...
*
Coroutine
Coroutines are computer program components that allow execution to be suspended and resumed, generalizing subroutines for cooperative multitasking. Coroutines are well-suited for implementing familiar program components such as cooperative task ...
*
Java virtual machine
A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally descr ...
*
Global interpreter lock
A global interpreter lock (GIL) is a mechanism used in computer-language Interpreter (computing), interpreters to synchronize the execution of Threads (computer science), threads so that only one native thread (per process) can execute basic ope ...
*
Fiber (computer science)
In computer science, a fiber is a particularly lightweight thread of execution.
Like threads, fibers share address space. However, fibers use cooperative multitasking while threads use preemptive multitasking. Threads often depend on the k ...
*
GNU Portable Threads
GNU Pth (Portable Threads) is a POSIX/ANSI- C based user space thread library for UNIX platforms that provides priority-based scheduling for multithreading applications. GNU Pth targets for a high degree of portability. It is part of the GNU Pr ...
*
Protothreads A protothread is a low-overhead mechanism for concurrent programming.
Protothreads function as Call stack, stackless, lightweight Thread (computer science), threads, or coroutines, providing a blocking context cheaply using minimal memory per proto ...
References
External links
*
Four for the ages,
JavaWorld article about Green threads
Green threads on Java threads FAQ
{{DEFAULTSORT:Green Threads
Threads (computing)
Java platform