forked from webtao520/golang_project
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
71 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
package main | ||
|
||
import ( | ||
"fmt" | ||
) | ||
|
||
func printer(c chan int) { | ||
|
||
// 开始无限循环等待数据 | ||
for { | ||
|
||
// 从channel中获取一个数据 | ||
data := <-c | ||
|
||
// 将0视为数据结束 | ||
if data == 0 { | ||
break | ||
} | ||
|
||
// 打印数据 | ||
fmt.Println(data) | ||
} | ||
|
||
// 通知main已经结束循环(我搞定了!) | ||
c <- 0 | ||
|
||
} | ||
|
||
func main() { | ||
|
||
// 创建一个channel | ||
c := make(chan int) | ||
|
||
// 并发执行printer, 传入channel | ||
go printer(c) | ||
|
||
for i := 1; i <= 10; i++ { | ||
|
||
// 将数据通过channel投送给printer | ||
c <- i | ||
} | ||
|
||
// 通知并发的printer结束循环(没数据啦!) | ||
c <- 0 | ||
|
||
// 等待printer结束(搞定喊我!) | ||
<-c | ||
|
||
} | ||
|
||
|
||
/** | ||
PS D:\goLang\github\golang_project\Go语言并发\示例:并发打印> go run 1.go | ||
1 | ||
2 | ||
3 | ||
4 | ||
5 | ||
6 | ||
7 | ||
8 | ||
9 | ||
10 | ||
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,7 @@ | ||
前面的例子创建的都是无缓冲通道。使用无缓冲通道往里面装入数据时,装入方将被阻塞, | ||
直到另外通道在另外一个 goroutine 中被取出。同样,如果通道中没有放入任何数据, | ||
接收方试图从通道中获取数据时,同样也是阻塞。发送和接收的操作是同步完成的。 | ||
|
||
下面通过一个并发打印的例子,将 goroutine 和 channel 放在一起展示它们的用法。 | ||
+ 案例 | ||
* 1.go |