码迷,mamicode.com
首页 > 其他好文 > 详细

go channel

时间:2017-09-08 11:54:28      阅读:231      评论:0      收藏:0      [点我收藏+]

标签:使用   读取   ring   pack   写入   put   map   type   for   

go channel

1、不同goroutine之间如何进行通讯?

  • 全局变量和锁同步
  • Channel

2、channel概念

  • 类似unix中管道(pipe)
  • 先进先出
  • 线程安全,多个goroutine同时访问,不需要加锁
  • channel是有类型的,一个整数的channel只能存放整数

3、channel声明

var 变量名 chan 类型

var test chan int
var test chan string
var test chan map[string]string
var test chan stu
var test chan *stu

4、channel初始化

使用make进行初始化

var test chan int
test = make(chan int, 10)

var test chan string
test = make(chan string, 10)

5、channel基本操作

  • 从channel读取数据
var testChan chan int
testChan = make(chan int, 10)
var a int
a = <- testChan
  • 从channel写入数据
var testChan chan int
testChan = make(chan int, 10)
var a int  = 10
testChan <- a

 channel初始化、基本操作示例:

package main

import "fmt"

type student struct {
	name string
}

func testmap(){
	var mapChan chan map[string]string
	mapChan = make(chan map[string]string, 10)
	m := make(map[string]string, 16)
	m["stu01"] = "123"
	m["stu02"] = "456"
	mapChan <- m
}

func teststruct(){
	var structChan chan student
	structChan = make(chan student, 10)

	stu := student {
		name: "stu01",
	}

	structChan <- stu
}

func teststruct1(){
	var structChan chan *student
	structChan = make(chan *student, 10)

	stu := student {
		name: "stu01",
	}

	structChan <- &stu
}

func main() {

	var stuChan chan interface{}
	stuChan = make(chan interface{}, 10)

	stu := student{name: "stu01"}

	stuChan <- &stu

	var stu01 interface{}
	stu01 = <-stuChan

	var stu02 *student
	stu02, ok := stu01.(*student)
	if !ok {
		fmt.Println("can not convert")
		return
	}

	fmt.Println(stu02)
}

goroutine和channel相结合示例

package main

import (
	"fmt"
	"time"
)

func write(ch chan int) {
	for i := 0; i < 100; i++ {
		ch <- i
		fmt.Println("put data:", i)
	}
}

func read(ch chan int) {
	for {
		var b int
		b = <-ch
		fmt.Println("get data:", b)
		time.Sleep(time.Second)
	}
}

func main() {
	intChan := make(chan int, 10)
	go write(intChan)
	go read(intChan)

	time.Sleep(100 * time.Second)
}

6、channel特点

  • channel阻塞
  • 带缓冲区的channel

如下所示,testChan只能放一个元素:

var testChan chan int
testChan = make(chan int)
var a int
a = <- testChan

如下所示,testChan是带缓冲区的chan,一次可以放10个元素:

var testChan chan int
testChan = make(chan int, 10)
var a int  = 10
testChan <- a

 

go channel

标签:使用   读取   ring   pack   写入   put   map   type   for   

原文地址:http://www.cnblogs.com/shhnwangjian/p/7493030.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!