1、多线程程序在单核上运行,就是并发
2、多线程程序在多核上运行,就是并行
因为是在CPU上,比如都有10个线程,每个线程执行10毫秒(进行轮询操作),从人的角度看,好像这10个线程都在运行,但是从微观上看,在某一个时间点看,其实只有一个线程在执行,这就是并发
因为是在多个CPU上(比如有10个CPU),比如有10个线程,每个线程执行10毫秒(各自在不同的CPU上执行),从人的角度看,这10个线程都在运行,并且从微观上看,在某一个时间点看,也同时有10个线程在执行,这就是并行
1.Go主线程(有程序员直接称为线程/也可以理解成进程):一个Go线程上,可以起多个协程,可以理解为协程是轻量级的线程
2.Go协程的特点
编写一个程序
1、在主线程中(也可以理解成进程)中,开启一个goroutine,改协程每隔1秒输出“hello,world”
2、在主线程中也每隔1秒“hello,golang”,输出10次后,退出程序
3、要求主线程和goroutine同时执行
4、画出主线程和协程执行流程图
package mainimport ("fmt""strconv""time"
)func test() {for i := 1; i <= 10; i++ {fmt.Println("test () hello,world" + strconv.Itoa(i))time.Sleep(time.Second)}
}func main() {go test() //开启了一个协程for i := 0; i <= 10; i++ {fmt.Println("main() hello,golang" + strconv.Itoa(i))time.Sleep(time.Second)}
}
/*
main() hello,golang0
test () hello,world1
test () hello,world2
main() hello,golang1
main() hello,golang2
test () hello,world3
test () hello,world4
main() hello,golang3
main() hello,golang4
test () hello,world5
test () hello,world6
main() hello,golang5
main() hello,golang6
test () hello,world7
test () hello,world8
main() hello,golang7
main() hello,golang8
test () hello,world9
main() hello,golang9
test () hello,world10
main() hello,golang10*/
介绍:为了充分利用多CPU的优势,在golang中,设置运行的CPU数目
1.go1.8后默认让程序运行在多个核上,可以不用设置了
2.go1.8前,要设置以下,可以更高效的利用CPU
package mainimport ("fmt""runtime"
)func main() {//获取当前系统CPU数量num := runtime.NumCPU()//这里设置num-1的CPU运行go程序runtime.GOMAXPROCS(num)fmt.Println("num=", num)
}
//num=8
1、全局变量加锁同步
2、channel