Golang Concurrent Programming

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang Common methods:

Package Mainimport ("FMT") func rand_generator_1 () int {return Rand. INT ()}func main () {FMT. Println (Rand_generator_1 ())}


Golang Generator:

The package Mainimport ("FMT" "Math/rand")/*** generator * Generates the appropriate data using functions based on known rights, and the asynchronous invocation saves a lot of time. * @author: Niuyufu */func rand_generator_1 () int {return Rand. int ()}//direct return channel Channelfunc rand_generator_2 () Chan int {//create Channel out: = Make (chan int)//Create Ctrip go func () {//execute continuously until program is interrupted for {// Writes data to the channel, and if no one reads it, it waits out <-rand. Int ()}} () return Out}func main () {//Generate random number as a service Rand_service_handler: = rand_generator_2 ()//read random number from service and print FMT. Println ("%dn", <-rand_service_handler) fmt. Println ("%dn", <-rand_service_handler) fmt. Println ("%dn", <-rand_service_handler)}


Golang multiplexing, high-concurrency version builder:

Package Mainimport ("FMT" "Math/rand")/*** multiplexing, high concurrency generator * Generates the appropriate data using functions based on known rights, and the asynchronous invocation saves a lot of time. * @author: Niuyufu */func rand_generator_1 () int {return Rand. int ()}//direct return channel Channelfunc rand_generator_2 () Chan int {//create Channel out: = Make (chan int)//Create Ctrip go func () {//execute continuously until program is interrupted for {// Writes data to the channel, and if no one reads it, it waits out <-rand. int ()}} () return out}//function rand_generator_3, return Channel (channel) func rand_generator_3 () Chan int {//Create two random number generator service Rand_service_ handler_1: = rand_generator_2 () rand_service_handler_2: = rand_generator_2 ()//create channel out: = Make (chan int)//create coprocessor go func () { for {///Read data from Generator 1, consolidate out <-<-rand_service_handler_1}} () go func () {for {//Read data in Generator 1, consolidate out <-<-rand_ Service_handler_2}} () return Out}func main () {//Generate random number as a service Rand_service_handler: = Rand_generator_3 ()// Reads the random number from the service and prints the FMT. Println ("%dn", <-rand_service_handler) fmt. Println ("%dn", <-rand_service_handler) fmt. Println ("%dn", <-rand_service_handler)}


Furture Technology of Golang

Package Mainimport ("FMT")/*** furture technology * Call a function without preparing parameters: This design provides a great degree of freedom and concurrency, and parameter invocation is fully decoupled from parameter invocation * @author: Niuyufu */// One query struct type query struct {//parameter Channelsql chan string//result Channelresult Chan string}//execute queryfunc execquery (q query) {// Start the coprocessor go func () {//Get input sql: = <-q.sql//access the database, output the result channel Q.result <-"get" + SQL} ()}func main () {//Initialize QUERYQ: = Query{make ( Chan string, 1), make (Chan string, 1)}//Execute query, note that there is no need to prepare parameters ExecQuery (q)//Prepare Parameters Q.sql <-"select * FROM table"// Gets the result of FMT. Println (<-q.result)}


Golang of the Concurrency cycle

Package Mainimport ("FMT")/*** concurrent loops * concurrency run n tasks at once, this bull x* @author: Niuyufu */func dosomething (i int, Xi int) {FMT.  Println ("i=%d,xi=%d", I, xi)}func main () {//Set up counter//here is like there are many tasks that need to be processed at once data: = []int{1, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3  , 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3, 2, 3, 1, 2, 3}n: = Len (data) Sem: = make (chan int, N)//After this for allows the CPU to fill up to run your task for I, Xi : = Range Data {//establishes the coprocessor go func (i int, Xi int) {dosomething (I, xi)//Count sem <-0} (I, xi)}fmt. PRINTLN ("Concurrent loop Start")//wait for end, view run results for I: = 0; i < N; i++ {<-sem}fmt. Println ("It's done." ")}


Golang's Chain filter technology

Package Mainimport ("FMT")/*** Chain Filter Technology * Concurrent filtering chain, only two simultaneous access per channel, good performance * @author: Niuyufu */func Generate (ch chan<-int {for I: = 2;; i++ {//fmt. Println ("generate:i:", i) ch <-i}}func Filter (in <-chan int, out chan<-int, Prime int) {for {/////Only output can re-create I: = < ;-in//fmt. Println ("Filter:in pop:", i) if i%prime! = 0 {//fmt. Println ("Filter:out add:", I) out <-I}}}//func main () {//result array var numbers []int//channel size 1ch: = make (chan int) go G Enerate (CH)//generate Gorouine occupies Channel:ch, the channel is occupied once for I: = 0; i < 1000; i++ {prime: = <-chnumbers = append (numbers, prime) fmt. Println (Prime, "N") Ch1: = make (chan int) go Filter (CH, ch1, Prime)//filter Gorouine also points to Channel:ch, channel occupied two times ch = ch1                  // Get through the two channels of//FMT. Println (<-CH1)}//fmt. Printf ("len=%d cap=%d slice=%v\n", Len (Numbers), Cap (numbers), numbers)}


Shared variables of Golang

The package Mainimport ("FMT" "Time")/*** shared variable * maintains both channels through a single process. Ensure consistency of data. * @author: Niuyufu *///shared variable has a read channel and a write channel composed of type Sharded_var struct {reader Chan intwriter chan int}//shared variable maintenance coprocessor func Sharded_v Ar_whachdog (v sharded_var) {go func () {///initial value var value int = 0for {//listen read/write channel, complete service Select {Case value = <-v.writer:case V.R Eader <-Value:}} ()}//timeout to avoid blocking func never_leak (ch Chan int) {//Initialize timeout, buffer 1timeout: = Make (chan bool, 1)// Starting the timeout association, because the cache is 1, it is not possible to leak go func () {time. Sleep (1 * time.  Second) Timeout <-true} ()//monitor channel, due to a timeout, cannot leak select {case <-ch://a read from CH have occurredcase <-timeout://the Read from CH have timed Out}}func main () {//Initialize, and start Maintenance coprocessor V: = Sharded_var{make (chan int), make (chan int)}sharded_var_whachdo G (v)//Read Initialize FMT. PRINTLN (<-v.reader)//Writes a value V.writer <-1//reads the newly written value of FMT. Println (<-v.reader)}


Golang time-out use of the Select

Package Mainimport ("FMT" "Time")/*** Select uses * Select to randomly filter the executable operation from the case and block if no action is available. * Use time-outs to avoid read blocking, use buffering to avoid write blocking * @author: Niuyufu */func Main () {timeout: = make (chan bool, 1) ch: = make (chan int)/per second produce true data go f UNC () {time. Sleep (1e9)//sleep one secondtimeout <-true} () select {Case <-ch:fmt. Println ("ch pop") case <-timeout:fmt. Println ("timeout!")}}


Golang the default value of the select operation

Package Mainimport ("FMT")/*** Select the default action * when there is no operational case, the default operation is called @author: Niuyufu */func Main () {ch1: = Make (chan i NT, 1) CH2: = Make (chan int, 1)//The co-operation can not only synchronize calls but also asynchronously invoke CH1 <-1//Synchronize select {case <-ch1:fmt. Println ("ch1 pop One Element") case <-ch2:fmt. Println ("CH2 pop One Element") default:fmt. PRINTLN ("Default")}}


Golang Select Verify that the channel is full?

Package Mainimport ("FMT")/*** Select Verify that the channel is full? * @author: Niuyufu */func Main () {ch1: = Make (Chan int., 1) ch1 <-1select {case Ch1 <-2:fmt. PRINTLN ("Channel isn't full!") Default:fmt. PRINTLN ("Channel is full!")}}


Producer consumers of Golang

Package Mainimport ("FMT" "Time") Func main () {ch: = do (chan int, 1) Timeout: = Make (chan bool, 1)//producer go func () {for I: = 0; I < 5; i++ {ch <-ifmt. Println ("produced:%d", I)}} ()//consumer var value int//set maximum operand for i: = 0; I < 10; i++ {//per second to produce true data go func () {time. Sleep (Ten * time. microsecond)//sleep one secondtimeout <-true} () select {Case value = <-ch:fmt. Println ("Consumed:%d", value) case <-timeout:fmt. Println ("timeout!")}}}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.