go和java线程,Go的多线程和pthread或Java线程有什么区别?
正如之前的答案所述,go例程并不一定與系統(tǒng)線程相對(duì)應(yīng),但是如果你現(xiàn)在必須提高多線程的性能,我發(fā)現(xiàn)以下內(nèi)容很有用:
The current implementation of the Go runtime will not parallelize this code by default. It dedicates only a single core to user-level processing. An arbitrary number of goroutines can be blocked in system calls, but by default only one can be executing user-level code at any time. It should be smarter and one day it will be smarter, but until it is if you want CPU parallelism you must tell the run-time how many goroutines you want executing code simultaneously. There are two related ways to do this. Either run your job with environment variable GOMAXPROCS set to the number of cores to use or import the runtime package and call runtime.GOMAXPROCS(NCPU). A helpful value might be runtime.NumCPU(), which reports the number of logical CPUs on the local machine. Again, this requirement is expected to be retired as the scheduling and run-time improve.
quote source
最大化我的i5處理器的一個(gè)示例程序就是這個(gè)(在htop中使用100%的所有4個(gè)核心):
package main
import (
"fmt"
"time"
"runtime"
)
func main() {
runtime.GOMAXPROCS(4) // Set the maximum number of threads/processes
d := make(chan string)
go boring("boring!", d, 1)
go boring("boring!", d, 2)
go boring("boring!", d, 3)
go boring("boring!", d, 4)
for i := 0; i < 10; i++ {
time.Sleep(time.Second);
}
fmt.Println("You're boring; I'm leaving.")
}
func boring(msg string, c chan string, id int) {
for i := 0; ; i++ {
}
}現(xiàn)在它實(shí)際上并沒(méi)有“做”任何事情,但是看看與其他語(yǔ)言(如Java)編寫(xiě)多線程應(yīng)用程序相比有多簡(jiǎn)短/簡(jiǎn)單/簡(jiǎn)單。
總結(jié)
以上是生活随笔為你收集整理的go和java线程,Go的多线程和pthread或Java线程有什么区别?的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: java函数求方程,Commons Ma
- 下一篇: mongodb3.2 java,Mong