search
HomeBackend DevelopmentGolangWhat is the difference between threads and processes in go language

Difference: 1. Thread is the smallest unit of program execution, while process is the smallest unit of resources allocated by the operating system. 2. A process consists of one or more threads. Threads are different execution routes of code in a process. 3. Thread context switching is much faster than process context switching. 4. Process switching requires maximum resources and is very inefficient; thread switching requires average resources and has average efficiency. 5. The process has its own stack and the stack is not shared between processes; the thread has its own stack and shares the heap.

What is the difference between threads and processes in go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

What are threads and processes?

A process

  • is a program with certain independent functions on a data set The A dynamic execution process
  • is an independent unit for resource allocation and scheduling by the operating system
  • It is the carrier for the operation of the application

Thread

  • Thread is a single sequential control process in program execution
  • It is the smallest unit of program execution flow
  • Is the basic unit of processor scheduling and allocation
  • A process can have one or more threads
  • The memory space of the program is shared between each thread

Task Scheduling

The task scheduling of most operating systems (Windows, Linux) adopts the time slice rotation preemptive scheduling method.
The scheduling method is as follows:

  • In a process, when a thread task is executed for a few milliseconds, it will be scheduled by the operating system kernel

  • Interrupt the processor through the hardware counter, force the thread to pause and put the thread's register into the memory

  • Determine which thread to execute next by looking at the thread list

  • Then restore the register of the thread from the memory, and finally resume the execution of the thread to execute the next task

This method guarantees Each thread is executed in turn. Since the execution efficiency of the CPU is very high and the time slice is very short, it quickly switches between tasks. It gives the impression that multiple tasks are being performed at the same time. This is what we Talk about concurrency.

What is the difference between threads and processes in go language

The difference between process and thread

    Thread is the smallest part of program execution Unit, and process is the smallest unit for the operating system to allocate resources
  • A process consists of one or more threads, and threads are different execution routes of code in a process
  • Thread context switching is much faster than process context switching
  • Process switching requires the largest resources and is very inefficient; thread switching requires average resources and has average efficiency .
  • The process has its own stack, the stack is not shared between processes, and is scheduled by the operating system
  • Threads have their own stack, share the heap, and are also scheduled by the operating system

Multi-threading and multi-core

Multi-core processor

refers to integration on one processor Multiple computing cores are installed to improve computing power. That is to say, there are multiple processing cores for true parallel computing, and each processing core corresponds to a kernel thread.

Kernel thread

Each processing core corresponds to a kernel thread.

For example:

A single-core processor corresponds to one core thread
  • A dual-core processor corresponds to two core threads
  • A quad-core processor corresponds Four kernel threads
  • Kernel Thread (KLT) is a thread directly supported by the operating system kernel. The thread is switched by the kernel. The kernel schedules the thread by operating the scheduler and is responsible for mapping the thread's tasks to each processor.

Hyper-threading technologyCurrently, processors use

Hyper-threading technology

to combine a physical processing core Simulated into two logical processing cores , that is, two kernel threads. So the computers we see are generally dual-core and four-thread, or four-core and eight-thread. In the operating system, we see that the number of CPUs is twice the number of actual physical CPUs. For example, dual-core and four-threads can see 4CPUs.

For example, the mbp I am currently writing the article on is an i7 6-core 12-thread:

What is the difference between threads and processes in go languagePrograms generally do not use kernel threads directly, but use the kernel A high-level interface for threads—Lightweight Process (LWP), which is what we often call

threads

.

CoroutinesCoroutines are based on threads and are more lightweight than threads. A thread can have multiple coroutines.

The purpose of coroutine

In traditional applications, a thread is usually created for network requests to complete business logic. If there are multiple requests, multiple threads will be created.
If you encounter a time-consuming I/O behavior, the thread will always be in a blocked state. If many threads are in this idle state (waiting for the thread to complete execution before executing), this will cause resource application If it is not thorough, the throughput capacity of the system will decrease.

The most common time-consuming I/O behavior is such as JDBC. The CPU will always wait for the return of the data I/O operation. At this time, the thread does not use the CPU to perform operations at all, but is in an idle state. Using too many threads at the same time will also bring more context switching overhead.

There are two solutions to the above problems:

  • Single thread plus asynchronous callback
    For example, Node.js, Java’s Vert.x
  • Coroutine
    The purpose of the coroutine is to give up the current coroutine schedule and execute the next task when a long-term I/O operation occurs to eliminate the overhead of ContexSwith

Characteristics of coroutines

  • Thread switching is scheduled by the operating system, and coroutines are scheduled by users themselves, thus reducing context switching and improving efficiency
  • The default Stack size of the thread is 1M, while the coroutine is more lightweight, close to 1K. Therefore, more coroutines can be opened in the same memory
  • Because the coroutines are on the same thread, competition can be avoided. 2. Use locks
  • Suitable for blocked and requiring a lot of concurrency Scenes. But it is not suitable for multi-threading of large amounts of calculations

The principle of coroutine

The process of coroutine :

  • When I/O blocking occurs, the scheduler of the coroutine will schedule it

  • By yielding the data stream immediately ( Actively give up), and record the data on the current stack

  • After the blocking is completed, immediately restore the stack through the thread, and put the blocking result on this thread to run

The thread running in the Coroutine is called Fiber. For example, the go keyword in Golang is actually responsible for opening a Fiber, let func logic run on it.

Because the suspension of the coroutine is completely controlled by the program and occurs in the user state; the blocking state of the thread is switched by the operating system kernel and occurs in the kernel state.
Therefore, the overhead of coroutines is much less than that of threads, and there is no overhead of context switching.

Comparison of threads and coroutines

##Comparison itemsThreadCoroutineOccupied resourcesThe initial unit is 1MB, fixed and immutableThe initial unit is generally 2KB , can be increased as needed Scheduling belongs to Completed by OS kernel Completed by user Switching overheadDesign mode switching (switching from user mode to kernel mode), refreshing of 16 registers, PC, SP and other registersOnly three register values ​​are modified: PC, SP , DX##Performance issuesData synchronization【 Related recommendations:
The resource occupancy is too high, frequent creation and destruction will cause serious performance problems The resource occupancy is small, and it will not bring Serious performance issues arise
Requires mechanisms such as locks to ensure data consistency and visibility Does not require multi-threaded locking mechanisms , so there is only one thread. There is no conflict in writing variables at the same time. Shared resources are controlled in the coroutine without locking. You only need to determine the status, so the execution efficiency is much higher than that of threads
Go video tutorial

, Programming teaching

The above is the detailed content of What is the difference between threads and processes in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Learn Go String Manipulation: Working with the 'strings' PackageLearn Go String Manipulation: Working with the 'strings' PackageMay 09, 2025 am 12:07 AM

Go's "strings" package provides rich features to make string operation efficient and simple. 1) Use strings.Contains() to check substrings. 2) strings.Split() can be used to parse data, but it should be used with caution to avoid performance problems. 3) strings.Join() is suitable for formatting strings, but for small datasets, looping = is more efficient. 4) For large strings, it is more efficient to build strings using strings.Builder.

Go: String Manipulation with the Standard 'strings' PackageGo: String Manipulation with the Standard 'strings' PackageMay 09, 2025 am 12:07 AM

Go uses the "strings" package for string operations. 1) Use strings.Join function to splice strings. 2) Use the strings.Contains function to find substrings. 3) Use the strings.Replace function to replace strings. These functions are efficient and easy to use and are suitable for various string processing tasks.

Mastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMastering Byte Slice Manipulation with Go's 'bytes' Package: A Practical GuideMay 09, 2025 am 12:02 AM

ThebytespackageinGoisessentialforefficientbyteslicemanipulation,offeringfunctionslikeContains,Index,andReplaceforsearchingandmodifyingbinarydata.Itenhancesperformanceandcodereadability,makingitavitaltoolforhandlingbinarydata,networkprotocols,andfileI

Learn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageLearn Go Binary Encoding/Decoding: Working with the 'encoding/binary' PackageMay 08, 2025 am 12:13 AM

Go uses the "encoding/binary" package for binary encoding and decoding. 1) This package provides binary.Write and binary.Read functions for writing and reading data. 2) Pay attention to choosing the correct endian (such as BigEndian or LittleEndian). 3) Data alignment and error handling are also key to ensure the correctness and performance of the data.

Go: Byte Slice Manipulation with the Standard 'bytes' PackageGo: Byte Slice Manipulation with the Standard 'bytes' PackageMay 08, 2025 am 12:09 AM

The"bytes"packageinGooffersefficientfunctionsformanipulatingbyteslices.1)Usebytes.Joinforconcatenatingslices,2)bytes.Bufferforincrementalwriting,3)bytes.Indexorbytes.IndexByteforsearching,4)bytes.Readerforreadinginchunks,and5)bytes.SplitNor

Go encoding/binary package: Optimizing performance for binary operationsGo encoding/binary package: Optimizing performance for binary operationsMay 08, 2025 am 12:06 AM

Theencoding/binarypackageinGoiseffectiveforoptimizingbinaryoperationsduetoitssupportforendiannessandefficientdatahandling.Toenhanceperformance:1)Usebinary.NativeEndianfornativeendiannesstoavoidbyteswapping.2)BatchReadandWriteoperationstoreduceI/Oover

Go bytes package: short reference and tipsGo bytes package: short reference and tipsMay 08, 2025 am 12:05 AM

Go's bytes package is mainly used to efficiently process byte slices. 1) Using bytes.Buffer can efficiently perform string splicing to avoid unnecessary memory allocation. 2) The bytes.Equal function is used to quickly compare byte slices. 3) The bytes.Index, bytes.Split and bytes.ReplaceAll functions can be used to search and manipulate byte slices, but performance issues need to be paid attention to.

Go bytes package: practical examples for byte slice manipulationGo bytes package: practical examples for byte slice manipulationMay 08, 2025 am 12:01 AM

The byte package provides a variety of functions to efficiently process byte slices. 1) Use bytes.Contains to check the byte sequence. 2) Use bytes.Split to split byte slices. 3) Replace the byte sequence bytes.Replace. 4) Use bytes.Join to connect multiple byte slices. 5) Use bytes.Buffer to build data. 6) Combined bytes.Map for error processing and data verification.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.