How to get a concurrent method
How to get a concurrent method?
type test struct {
foo uint8
bar uint8
}
func NewTest(arg1 string) (*test, os.Error) {...}
func (self *test) Get(str string) ([]byte, os.Error) {...}
I think that all code for method Get()
should be put inner of go func()
, and then to use a channel.
func (self *test) Get(str string) ([]byte, os.Error) {
go func() {
// Code for this method.
}()
}
- Would there be a problem if it's call开发者_如何学运维ed another method from
Get()
? Or would it also has to be concurrent?
Take a look at the An example package section in The Go Language Specification, which is a complete Go package that implements a concurrent prime sieve, using go statements and channels.
For a detailed description of how it works, see the Go Tutorial section on Prime numbers. Also, look at the Go Tutorial section on Multiplexing.
Read the Effective Go section on Concurrency.
Finally, read the relevant sections of The Go Language Specification e.g. the sections on Go statements, Channel types, and Select statements.
Yes, you can call another method from your Get() method. Since a method call is not a concurrent go statement, it will execute immediately, before executing the next statement.
The way you get concurrency in go is to use the keyword "go" in front of functions you want to execute concurrently:
func bar () { ... }
func foo () { go bar() go bar() go bar() ... code that waits for all the bars to close ... }
That's all it takes to run 3 bars at the same time. PS: You might want to provide an example in a language you are familiar with, C++ / Perl / Python / whatever since the go code fragment you included wasn't much help. I realize you probably speak English better than I speak your native language, but you might also want to get some assistance formulating your question more clearly.
Hotei
精彩评论