This is a creation in Article, where the information may have evolved or changed.
1. return value using Channel
Func Main () {//generate random numbers as a serviceRandservice: =Randgenerator ()//read random numbers from the service and printFmt. Printf ("%d\n", <-Randservice)} Func randgenerator () Chanint { //Create a channel out: = Make (chanint) //Create a co-processgo func () { for { //writes data to the channel and waits if no one reads out<-Rand. Int ()}} ()return out}
2. Parameters using Channels
//a query structure bodyType querystruct { //parameter ChannelSQL Chanstring //Results ChannelResult Chanstring}//Execute Queryfunc ExecQuery (q query) {//Start the processgo func () {//Get inputsql: = <-Q.sql//Accessing the database, outputting the result channelQ.result <-"Get"+SQL} ()}func main () {//Initialize QueryQ: = Query{make (chanstring,1), make (chanstring,1)} //Execute Query, note that there is no need to prepare parameters when executingExecQuery (q)//Prepare ParametersQ.sql <-"select * FROM table" //Get ResultsFmt. Println (<-Q.result)}
3. Concurrent Loops
Func dosomething (numint) (sumint) { forI: =1; I <=Ten; i++{fmt. Printf ("%d +%d =%d\n", num, num + i, num + num +i) Sum= sum + num +i}returnSum}func Testloop () {//set up a counter with a channel size of CPU cores varNUMCPU =Runtime. NUMCPU () fmt. Printf ("numcpu =%d\n", NUMCPU) SEM:=make (chanint, NUMCPU); //For loop bodyData: = []int{1, One, +, to, A,Wuyi, A, in,Bayi, the} for_,v:=Range Data {//establish a co-processGo func (Vint) {fmt. Printf ("dosomething (%d) ... \ n", v) sum:=dosomething (v); //CountSEM <-sum; } (v); } //wait for the loop to end varTotalint=0 forI: =0; I < len (data); i++{temp:= <-sem fmt. Printf ("%d <-sem\n", temp) Total= Total +temp} fmt. Printf ("Total =%d\n", Total)} Func Main () {Testloop ()}
4. Using channel to calculate prime numbers
//Send the sequence 2, 3, 4, ... to channel ' in '.Func Generate (Ch chanint) { forI: =2; ; i++{ch<-I//Send ' i ' to Channel ' in '. }}//Copy the values from channel ' on ' to channel ' out ',//removing those divisible by ' prime '.Func Filter (inchChanint, outChanint, primeint) { for{i:= <-inch //Receive valuefrom ' in '. ifI%prime! =0 { out<-I//Send ' i ' to ' out '.}}}func Main () {inch: = Make (chanint) Go Generate (inch)//Launch Generate goroutine. forI: =0; I < -; i++{prime:= <-inchprint (Prime,"\ n") out: = Make (chanint) Go Filter (inch, out, Prime)inch= out }}
5. Read and write shared variables
//shared variables consist of a read channel and a write channelType Shardedvarstruct{Reader Chanintwriter Chanint}//Shared Variable Maintenance co-processfunc Whachdog (v shardedvar) {go func () {//Initial value varValueint=0 for { //listen to read and write channels, complete service Select { CaseValue = <-V.writer: CaseV.reader <-Value:}} } ()}func main () {//Initialize and start the maintenance processV: = Shardedvar{make (chanint), make (chanint)} whachdog (v)//Read initial valueFmt. Println (<-V.reader)//Write a valueV.writer <-1 //read the newly written valueFmt. Println (<-V.reader)}
You can also visit my Raspberry Pi blog address:
http://www.codeforfun.info/