Understand go concurrency

CONTENT

(click to expand or hide)
  1. What is Concurrency?
  2. Why we need to think about Concurrency?
  3. What is a Process?
  4. What is a Thread?
    1. Thread_States
    2. C10k Problem
  5. Goroutines
    1. Scheduling
  6. Channels
    1. Range Channel
    2. Buffered Channel
    3. Unbuffered Channel
    4. Owner Channels
  7. Select
  8. Sync
    1. Mutex
    2. Atomic
    3. Conditional Variable
    4. Sync Once
    5. Sync Pool

What is Concurrency?

  • Concurrency is about multiple thinks happening at the same time.
  • Go provides built in support for concurrency.

Why we need to think about Concurrency?

func Add(numbers[]int) int64 {
    var sum int64
    for _, number := range numbers {
        sum += int64(number)
    }
    return sum
}

If we have millions of numbers, it's gonna take a lot of time to add them up. When we run to the function it's running in one core and the other cores are idle. Our target is to run the function in multiple cores.

  • Concurrency is composition of independent execution computations, which may or may not run in parallel.
  • Parallelism is the ability to execute multiple computations in simultaneous.
  • Concurrency enables parallelism.

What is a Process?

  • An instance of a running program.
  • Process provides environment for running a program.
Stacks
Heap
Data
Code
  • OS -> Allocate memory.
  • Code -> Machine instructions.
  • Data -> Global data
  • Stacks -> Used to store local variables.
  • Heap -> Dynamic memory allocation.

What is a Thread?

  • Threads are the smallest units of execution.
  • Process has at least one thread main thread
  • Threads share the same memory space.
  • Processes can have multiple threads.
Heap
Data
Code
Thread-1 ~ Thread-2
Stack ~ Stack
Registers ~ Registers
PC~PC
  • Threads run independently of each other.
  • Threads share the same memory space.
  • Threads can run concurrently in parallel.

Thread States

  • When the process is created, the main thread is put into the ready queue. It's in the runnable state.
  • Once the CPU is available, the thread starts to execute and each thread given a time slice.
  • If that time slice is over, the thread is put back into the ready queue.
  • If the thread is blocked, it's put into the blocked queue.

Runnable --Scheduler Dispatch--> Executing --I/O or event wait--> Waiting --I/O or event completion--> Runnable

C10k Problem

The C10k problem is the problem of optimizing network sockets to handle a large number of clients at the same time. alt text

  • OS gives a fixed stack size for each thread. It's dependent on the hardware. So if I have a 8GB of memory and 8k kbytes stack, then theoretically I create 1000 thread. you can check with this command ulimit -a

Go's Concurrency Tool Set

  • Goroutines -> Goroutines are concurrently executing functions.
  • Channels -> Channels are used to communicate between goroutines.
  • Select -> Select is used to multiplex the channels.
  • Sync -> Sync is used to synchronize the execution of goroutines.

Goroutines

  • Goroutines extremely lightweight.
  • Starts with 2kb of stack, which grows and shrinks as needed.
  • Low CPU overhead.
  • Channels are used for the communication of data between goroutines. Sharing of memory can be avoided by using channels.
  • Go runtime creates worker OS threads.
  • Goroutines run in the context of OS thread.

M:N Scheduling

  • Go Scheduler runs in user space.
  • Go Scheduler runs in the context of OS thread.
  • Go runtime create number of worker OS threads, equal to the number of CPUs (GOMAXPROCS).
  • Go Scheduler distributes runnable goroutines over multiple OS threads.

Channels

  • Channels are used to communicate between goroutines.
  • Sync with Goroutines.
  • Typed.
  • Thread safe.
  • example-1: var ch chan <Type> && ch = make(chan <Type>)
  • example-2:ch := make(chan <Type>) allocate memory for channel.
  • Pointer operator is used for sending and receiving the value from channel. The arrow indicates the direction of the communication.
    • Send: ch <- <value>
    • Receive: <value> = <- ch
    • Close: Close(ch) close the channel.
  • Receive returns two value, the first one is a received value from the channel and the second one is a boolean value.
    • If the channel is closed, the second value will be false.
    • If the channel is not closed, the second value will be true.

Range Channel

  • Iterate over values received from a channel.
  • Loop automatically stops when the channel is closed.
  • Range does not return a second boolean value.

Unbuffered Channel

  • make(chan <Type>) allocate memory for channel.

Buffered Channel

  • make(chan <Type>, <Size>) allocate memory for channel with buffer size.
  • in-memory FIFO queue.
  • Asynchronous.

Ownership of channel avoids

  • Deadlocking by writing to nil channel.
  • Closing a nil channel.
  • Writing to a closed channel.
  • Closing a channel more than one

These are the reasons getting panic.

Select

select {
case <-ch1:
    // do something
case <-ch2:
    // do something
default:
    // do something
}
  • Empty select block will block forever.
  • Select is like this switch statement.
  • Select will block until any of the case is ready.
  • With select we can implement a non-blocking communication and timeout.
  • Select on nil channel will block forever.

Sync Package

Channels are great for communication between goroutines but what if we have like caches, registries and state which are big to sent over the channel and we want access to these data to be concurrent safe, so that only one goroutine has access at a time.

Mutex

  • Used for protecting shared resources.
  • sync.Mutex - Provide exclusive access to a resource.
mu.Lock()
balance += amount
mu.Unlock()
mu.Lock()
defer mu.Unlock()
balance += amount
  • sync.RWMutex - Allow multiple readers. Write lock is exclusive.
  • Mutex is used guards access to a shared resource.
  • The critical section represents the bottleneck between the goroutines.

###Atomic

Similar Resources

Read k8S-source-code notes, help quickly understand the K8S-code organization rules

Read k8S-source-code notes, help quickly understand the K8S-code organization rules

K8S源码阅读笔记 以下笔记针对 kubernetes V1.23.1(截至2022年01月01日最新版本),并不保证对其它版本的有效性 一、架构图 二、阅读前准备 由于kubernetes项目巧妙的设计和代码高度的封装性,建议在阅读代码前,尽可能的进行以下内容的准备: 1. 编程知识配备 编程语准

Feb 16, 2022

Concurrency-safe Go caching library with expiration capabilities and access counters

cache2go Concurrency-safe golang caching library with expiration capabilities. Installation Make sure you have a working Go environment (Go 1.2 or hig

Jan 1, 2023

A simple logging interface that supports cross-platform color and concurrency.

A simple logging interface that supports cross-platform color and concurrency.

WLog Package wlog creates simple to use UI structure. The UI is used to simply print to the screen. There a wrappers that will wrap each other to crea

Sep 26, 2022

Concurrency-safe Go caching library with expiration capabilities and access counters

cache2go Concurrency-safe golang caching library with expiration capabilities. Installation Make sure you have a working Go environment (Go 1.2 or hig

Dec 31, 2022

Code Generation for Functional Programming, Concurrency and Generics in Golang

goderive goderive derives mundane golang functions that you do not want to maintain and keeps them up to date. It does this by parsing your go code fo

Dec 25, 2022

A sync.WaitGroup with error handling and concurrency control

go-waitgroup How to use An package that allows you to use the constructs of a sync.WaitGroup to create a pool of goroutines and control the concurrenc

Dec 31, 2022

golang worker pool , Concurrency limiting goroutine pool

golang worker pool 中文说明 Concurrency limiting goroutine pool. Limits the concurrency of task execution, not the number of tasks queued. Never blocks su

Dec 19, 2022

gpool - a generic context-aware resizable goroutines pool to bound concurrency based on semaphore.

gpool - a generic context-aware resizable goroutines pool to bound concurrency. Installation $ go get github.com/sherifabdlnaby/gpool import "github.c

Oct 31, 2022

Structured Concurrency in Go

nursery: structured concurrency in Go RunConcurrently( // Job 1 func(context.Context, chan error) { time.Sleep(time.Millisecond * 10)

Dec 27, 2022

Concurrency limiting goroutine pool

workerpool Concurrency limiting goroutine pool. Limits the concurrency of task execution, not the number of tasks queued. Never blocks submitting task

Dec 28, 2022

concurrency utilities

concurrent concurrent.Map: backport sync.Map for go below 1.9 concurrent.Executor: goroutine with explicit ownership and cancellable concurrent.Map be

Dec 28, 2022

Pholcus is a distributed high-concurrency crawler software written in pure golang

Pholcus is a distributed high-concurrency crawler software written in pure golang

Pholcus Pholcus(幽灵蛛)是一款纯 Go 语言编写的支持分布式的高并发爬虫软件,仅用于编程学习与研究。 它支持单机、服务端、客户端三种运行模式,拥有Web、GUI、命令行三种操作界面;规则简单灵活、批量任务并发、输出方式丰富(mysql/mongodb/kafka/csv/excel等

Dec 30, 2022

Helper library for full uint64 randomness, pool backed for efficient concurrency

fastrand64-go Helper library for full uint64 randomness, pool backed for efficient concurrency Inspired by https://github.com/valyala/fastrand which i

Dec 5, 2021

dagger is a fast, concurrency safe, mutable, in-memory directed graph library with zero dependencies

dagger is a fast, concurrency safe, mutable, in-memory directed graph library with zero dependencies

dagger is a blazing fast, concurrency safe, mutable, in-memory directed graph implementation with zero dependencies

Dec 19, 2022

Concurrency in Go video course with in depth explanations & examples

Concurrency  in Go video course with in depth explanations & examples

Concurrency in Go Summary Coding Examples Introduction to Concurrency Go Routines Channels Select Concurrency Patterns Atomics Wait Groups - sync.Wait

Dec 26, 2022

yakv is a simple, in-memory, concurrency-safe key-value store for hobbyists.

yakv is a simple, in-memory, concurrency-safe key-value store for hobbyists.

yakv (yak-v. (originally intended to be "yet-another-key-value store")) is a simple, in-memory, concurrency-safe key-value store for hobbyists. yakv provides persistence by appending transactions to a transaction log and restoring data from the transaction log on startup.

Feb 24, 2022

This repository collects common concurrency patterns in Golang

Go Concurrency Patterns This repository collects common concurrency patterns in Golang Materials Concurrency is not parallelism Go Concurrency Pattern

Jan 9, 2023

Concurrency patterns in Go

Concurrency patterns in Go

Dec 28, 2022

File Processor in Concurrency Pattern using Golang goroutine.

 File Processor in Concurrency Pattern using Golang goroutine.

File Processor in Concurrency Pattern Implement a file processor solution in concurrency pattern using Golang goroutine. Get Started Run docker-compos

Sep 16, 2022
slang 🐕‍🦺 | a Programing language written to understand how programing languages are written

slang ??‍?? goal was to learn how a interpreter works, in other works who does these programing languages i use on daily basis works behind the seen h

Nov 18, 2021
Concurrency patterns in Go

Concurrency patterns in Go

Dec 28, 2022
Practical concurrency guide in Go, communication by channels, patterns

Go Concurrency Guide This guide is built on top of the some examples of the book Go Concurrency in Go and Go Programming Language Race Condition and D

Dec 28, 2022
A faster RWLock primitive in Go, 2-3 times faster than RWMutex. A Go implementation of concurrency control algorithm in paper

Go Left Right Concurrency A Go implementation of the left-right concurrency control algorithm in paper <Left-Right - A Concurrency Control Technique w

Jan 6, 2023
Go-concurrency-patterns - Sample concurrency patterns with Goroutines

About This sample project provides some concurrency pattern examples in Go using

Feb 21, 2022
A minimalist Go PDF writer in 1982 lines. Draws text, images and shapes. Helps understand the PDF format. Used in production for reports.
A minimalist Go PDF writer in 1982 lines. Draws text, images and shapes. Helps understand the PDF format. Used in production for reports.

one-file-pdf - A minimalist PDF generator in <2K lines and 1 file The main idea behind this project was: "How small can I make a PDF generator for it

Dec 11, 2022
The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework.

jin About The jin is a simplified version of the gin web framework that can help you quickly understand the core principles of a web framework. If thi

Jul 14, 2022
slang 🐕‍🦺 | a Programing language written to understand how programing languages are written

slang ??‍?? goal was to learn how a interpreter works, in other works who does these programing languages i use on daily basis works behind the seen h

Nov 18, 2021
It's so many regular expression forms are difficult to understand, such as perl, python, grep awk

Introduction Jamie Zawinski: Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems. It

Mar 31, 2022
Basic Kubernetes operator that have multiple versions in CRD. This operator can be used to experiment and understand Operator/CRD behaviors.

add-operator Basic Kubernetes operator that have multiple versions in CRD. This operator can be used to experiment and understand Operator/CRD behavio

Dec 15, 2021