This is a creation in Article, where the information may have evolved or changed.
This problem can be used as a pen test, now given the following conditions
go func() { for i := 1; i < 10; i++ { println(2*i - 1) }}()go func() { for i := 1; i < 10; i++ { println(2 * i) }}()
lets you combine odd and even in a variety of ways, and print the natural number, the topic is simple, think for a few seconds, and see your implementation ... Well, my implementation is relatively low, there is no way, Golang code how to write all that counseling like ...
1. The first way
package mainimport ("fmt""time")var count = 15func ping(c chan<- int) {for i := 1; i < count; i++ {c <- 2*i - 1}}func pong(c chan<- int) {for i := 1; i < count; i++ {c <- 2 * i}}func print(ch <-chan int) {for {msg := <-chfmt.Println(msg)time.Sleep(time.Millisecond * 50)}}func main() {ch := make(chan int)go ping(ch)go pong(ch)go print(ch)var input stringfmt.Scanln(&input)}
The above code, if the
go print(ch) 改成下面这样 channel不使用传参的形式而是直接使用全局的变量可以吗?for { msg := <-ch fmt.Println(msg) time.Sleep(time.Millisecond * 50)}如果不行的话那是为什么?
2. The second way
package mainimport ("fmt""runtime"// "time")var count = 15func main() {runtime.GOMAXPROCS(1)go func() {for i := 1; i < count; i++ {fmt.Println(2 * i)runtime.Gosched()}}()go func() {for i := 1; i < count; i++ {fmt.Println(2*i - 1)runtime.Gosched()}}()var input stringfmt.Scanln(&input)}
The second way, enable two goroutinue in the main function think about it, swap out their code location. such as this:
go func() { for i := 1; i < count; i++ { fmt.Println(2*i - 1) runtime.Gosched() }}()go func() { for i := 1; i < count; i++ { fmt.Println(2 * i) runtime.Gosched() }}()
These two ways are actually I forcibly lifted a chestnut, may not be too realistic, but if understand golang internal structure, the above problems are not true, the next detail I will be in later articles in the above code as an example to explain the channel data structure.