"Golang" Go language, wrap variable package for concurrent requests

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.
Package Mainimport ("FMT"    "Sync"    " Time")type Waitgroupwrapper struct {sync. Waitgroup}func (w *waitgroupwrapper) Wrap (CB func (Argvs ... interface{}), Argvs ... interface{}) {W.add (1 ) go func () {CB (Argvs ...) W.done ()} ()}type MyStructstruct{ AgeintNamestringSexBOOL}func getage (Argvs ...Interface{}) {age:= argvs[0]. (int) my:= argvs[1]. (*mystruct) My. Age=Age Time . Sleep (time. Second*1) fmt. Println (" Age-Done")}func GetName (Argvs ...Interface{}) {name:= argvs[0]. (string) my:= argvs[1]. (*mystruct) My. Name=name time. Sleep (time. Second*2) fmt. Println ("name Done")}func getsex (Argvs ...Interface{}) {my:= argvs[0]. (*mystruct) My. Sex=falseTime . Sleep (time. Second*3) fmt. Println ("Sex Done")}func Main () {varWG Waitgroupwrappervarmy MyStruct WG. Wrap (Getage,Ten, &my) WG. Wrap (GetName,"Test", &my) WG. Wrap (Getsex,&my) WG. Wait () fmt. Println (My)}

This red code, do things on the need to parallel the function of a package, when all the functions are completed, will not be returned.

$ time./done doing done{ten  false }real    0m3.011suser    0m0.001ssys    0m0.005s

In the current business, one of the user requests, need to query multiple NoSQL, in order to not serial wait, made an asynchronous wrap package, each query starts a go routine itself.

Of course, there are other parallel network/io requests can also do this, the use of interface variables, specific implementation functions and callers need to understand the type of each parameter.

Related Article

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.