Essentially, goroutine is a coroutine.
The difference is that Golang encapsulates and processes goroutine scheduling in many aspects such as runtime and system calls. When encountering long-term execution or system calls, it will actively use the CPU of the current goroutine to (P) Transfer it out so that other goroutines can be scheduled and executed. That is, Golang supports coroutines from the language level.
One of the major features of Golang is that it natively supports coroutines at the language level. You can create a coroutine by adding the go keyword in front of a function or method. (Recommended learning: go)
Coroutine is a lightweight thread implementation in the Go language and is managed by the Go runtime.
GO version: go version go1.4.2 linux/amd64
Test environment:
[root@localhost mpro]# more /proc/cpuinfo | grep "model name" model name : Intel(R) Core(TM) i5-4590 CPU @ 3.30GHz model name : Intel(R) Core(TM) i5-4590 CPU @ 3.30GHz model name : Intel(R) Core(TM) i5-4590 CPU @ 3.30GHz model name : Intel(R) Core(TM) i5-4590 CPU @ 3.30GHz [root@localhost mpro]# [root@localhost mpro]# grep MemTotal /proc/meminfo MemTotal: 3868776 kB [root@localhost mpro]# getconf LONG_BIT 64 [root@localhost mpro]# more /etc/redhat-release CentOS Linux release 7.1.1503 (Core)
Test case:
package main import ( "time" ) func main() { for i := 0; i < 200000; i++ { go func() { time.Sleep(5 * time.Second) }() } time.Sleep(10 * time.Second) }
Before executing the program:
top - 18:53:19 up 19 min, 3 users, load average: 0.00, 0.04, 0.11 Tasks: 522 total, 1 running, 521 sleeping, 0 stopped, 0 zombie %Cpu(s): 0.1 us, 0.2 sy, 0.0 ni, 99.6 id, 0.0 wa, 0.0 hi, 0.1 si, 0.0 st KiB Mem : 3868776 total, 3327732 free, 235764 used, 305280 buff/cache KiB Swap: 2097148 total, 2097148 free, 0 used. 3397344 avail Mem
After executing the program:
top - 18:53:37 up 19 min, 3 users, load average: 0.00, 0.04, 0.11 Tasks: 524 total, 1 running, 523 sleeping, 0 stopped, 0 zombie %Cpu(s): 1.2 us, 10.6 sy, 0.0 ni, 88.2 id, 0.0 wa, 0.0 hi, 0.1 si, 0.0 st KiB Mem : 3868776 total, 2793732 free, 752512 used, 322532 buff/cache KiB Swap: 2097148 total, 2097148 free, 0 used. 2880016 avail Mem
Summary: 200,000 coroutines occupy 500M of memory and 500,000 KB
On average, one coroutine occupies 2.5KB
The above is the detailed content of How much memory does golang coroutine occupy?. For more information, please follow other related articles on the PHP Chinese website!