This is a creation in Article, where the information may have evolved or changed. Here's a package that controls the amount of Golang gowork, and of course you can actually do it yourself, just to be more strikes each time. If it's just a goroutine, it's not necessary to use it, and of course this package is supported. The actual principle: the user is informed of the number of mergers to be initiated, and then the package will be initiated as a working pool of the amount of work. After that, the program apes just have to work in the pool. What you need, of course, is your worker. Prototype: Type workfunction func (req interface{}, res interface{}) can also be used to actually handle the function, prototype and worker, At the same time, when it's used, Gowork will be able to move the task parameters req to the normal function, what you need to do is pass through the req to get the usual results, and of course you can not do that. Use: Control the amount of time to 5,new a workmanager to manage goroutine, through
NewGoroutine啟動worker池,然後就可以AddRequest發布任務去執行了。
Package Mainimport ("FMT" "github.com/qianlnk/gowork") type people struct {Id int Name string}func SayHello (Request, Response interface{}) {req: = Request. (people) fmt. Printf ("Hello, I ' m%s, My ID is%d.\n", req. Name, req. ID)}func singsong (Request, Response interface{}) {req: = Request. ( People) fmt. Printf ("My ID is%d, what I'll sing is test_%s\n", req. Id, req. Name)}func Main () {wm: = Gowork. Newworkmanager () Wm. Newgoroutine ("SayHello", 5, SayHello, nil) wm. Newgoroutine ("SingSong", 5, singsong, nil) go func () {for i: = 1; i <; i++ {pl: = people{ Id:i, Name:fmt. Sprintf ("hello%d", I),} wm. Addrequest ("SayHello", PL)} wm. Done ("SayHello")} () for I: = 0; I < 20; i++ {pl: = people{id:i, name:fmt. Sprintf ("song%d", I),} wm. Addrequest ("singsong", PL)} wm. Done ("SingSong")}
Of course, if you're willing, you can also start a goroutine. The program will wait for the task to be completed and complete its completion. can be used to move github:https://github.com/qianlnk/gowork