我有三个这样的并发例程,
func Routine1() {
Print (value a, value b, value c)
Print (value a, value b, value c)
Print (value a, value b, value c)
}
func Routine2() {
Print (value e, value f, value g)
Print (value e, value f, value g)
Print (value e, value f, value g)
}
func Routine3() {
Print (value x, value y, value z)
Print (value x, value y, value z)
Print (value x, value y, value z)
}
func main() {
go …Run Code Online (Sandbox Code Playgroud) 如果我错了,请纠正我.只要我知道,goroutine大致类似于线程.所以如果我用不同的参数生成相同的函数,前缀为go.它应该工作得很好吗?
package main
import "fmt"
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
go f("direct")
go f("redirect")
//var input string
//fmt.Scanln(&input)
}
Run Code Online (Sandbox Code Playgroud)
实际产量:
rahul@g3ck0:~/programs/go$ go run goroutine.go
rahul@g3ck0:~/programs/go$
Run Code Online (Sandbox Code Playgroud)
我刚回来提示.
预期产量:
direct : 0
direct : 1
direct : 2
redirect : 0
redirect : 1
redirect : 2
Run Code Online (Sandbox Code Playgroud)
不一定是相同的顺序.
无法理解这种奇怪的行为.我错过了什么吗?
编辑:添加扫描语句可以解决它.但有没有更好的方法呢?
环境:OS X 10.8,Go 1.0.2
我创建一个缓冲区大小为2的通道,然后如果我写通道三次,它将抛出错误:
扔:所有的goroutines都睡着了 - 僵局!
当然,这是正确的.
但是如果我在goroutines中写入通道四次或更多次,它工作正常,为什么?频道的容量是2,为什么goroutines会忽略或忽略容量设置?我评论了读取通道代码,因此没有人会读取通道并保存容量.我也用time.Sleep等待所有goroutines完成他们的工作.
请查看以下代码:package main
//import "fmt"
func main() {
c := make(chan int, 2)
/*c <- 1
c <- 2
c <- 3*/
for i:=0; i<4; i++ {
go func(i int) {
c <- i
c <- 9
c <- 9
c <- 9
}(i)
}
time.Sleep(2000 * time.Millisecond)
/*for i:=0; i<4*2; i++ {
fmt.Println(<-c)
}*/
}
Run Code Online (Sandbox Code Playgroud)
有人会请点击一下吗?多谢你们.
我正在研究一些Go的并发模式.我看着使用goroutine和输入/输出通道实现后台工作程序,并注意到当我将新作业发送到接收通道(基本上将新作业排入队列)时,我必须在goroutine中执行它,否则调度会搞乱.含义:
for _, jobData := range(dataSet) {
input <- jobData
}
Run Code Online (Sandbox Code Playgroud)
go func() {
for _, jobData := range(dataSet) {
input <- jobData
}
}()
Run Code Online (Sandbox Code Playgroud)
对于更具体的东西,我玩了一些无意义的代码(这里是去游乐场):
package main
import (
"log"
"runtime"
)
func doWork(data int) (result int) {
// ... some 'heavy' computation
result = data * data
return
}
// do the processing of the input and return
// results on the output channel
func Worker(input, output chan int) {
for data := range …Run Code Online (Sandbox Code Playgroud) package main
import (
//"time"
"runtime"
"fmt"
)
func main() {
//time.Sleep(100 * time.Millisecond)//By adding this number of goroutine increases
fmt.Println(runtime.NumGoroutine())
}
Run Code Online (Sandbox Code Playgroud)
我试图找出程序中的goroutines数量.我的代码在这里.编码时我注意到默认的goroutines数是4.
为了我:
还有什么?
通过添加time.Sleep(上图),goroutines的数量增加到5.这是什么原因?
我希望我的常规工作者(ProcessToDo()在下面的代码中)等待,直到关闭之前处理所有"排队"工作.
工作程序具有"待办事项"通道(缓冲),通过该通道向其发送工作.它有一个"完成"通道告诉它开始关机.文档说如果满足多个选择,通道上的选择将选择"伪随机值"...这意味着在完成所有缓冲工作之前触发关闭(返回).
在下面的代码示例中,我希望打印所有20条消息...
package main
import (
"time"
"fmt"
)
func ProcessToDo(done chan struct{}, todo chan string) {
for {
select {
case work, ok := <-todo:
if !ok {
fmt.Printf("Shutting down ProcessToDo - todo channel closed!\n")
return
}
fmt.Printf("todo: %q\n", work)
time.Sleep(100 * time.Millisecond)
case _, ok := <-done:
if ok {
fmt.Printf("Shutting down ProcessToDo - done message received!\n")
} else {
fmt.Printf("Shutting down ProcessToDo - done channel closed!\n")
}
close(todo)
return
}
}
}
func main() …Run Code Online (Sandbox Code Playgroud) package main
import (
"fmt"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
fmt.Println(runtime.GOMAXPROCS(0))
// s := "hello world \n"
for i := 0; i < 100; i++ {
go func(n int) {
fmt.Println(n, i)
}(i)
}
fmt.Scanln()
}
Run Code Online (Sandbox Code Playgroud)
我只是想知道为什么n不等于i每一个例程.
也i有时具有相同的值在上一次调用.
这段代码有什么问题?
我有以下golang程序;
package main
import (
"fmt"
"net/http"
"time"
)
var urls = []string{
"http://www.google.com/",
"http://golang.org/",
"http://yahoo.com/",
}
type HttpResponse struct {
url string
response *http.Response
err error
status string
}
func asyncHttpGets(url string, ch chan *HttpResponse) {
client := http.Client{}
if url == "http://www.google.com/" {
time.Sleep(500 * time.Millisecond) //google is down
}
fmt.Printf("Fetching %s \n", url)
resp, err := client.Get(url)
u := &HttpResponse{url, resp, err, "fetched"}
ch <- u
fmt.Println("sent to chan")
}
func main() {
fmt.Println("start")
ch := make(chan …Run Code Online (Sandbox Code Playgroud) 每次for循环迭代时我都会在goroutine中运行一个函数,而我正在使用它sync.WaitGroup来确保goroutine都完成.但是,我正在用计数器测试并发性的奇怪行为.在下面的例子中,我试图跟踪使用4个不同的技术(线程数的w,x,y,z),并获得4个不同的结果.我理解的唯一结果是x,因为它在for循环中递增.我在这里错过了什么?
package main
import "fmt"
import "sync"
var w = 0
func main() {
x := 0
y := 0
z := 0
var wg sync.WaitGroup
for i := 0; i < 10000; i++ {
wg.Add(1)
x++
go func() {
z++
test(&y)
wg.Done()
}()
}
wg.Wait()
fmt.Println(w, x, y, z) // 8947 10000 8831 8816
}
func test(y *int) {
w++
*y++
}
Run Code Online (Sandbox Code Playgroud) 我目前有一个MQTT代码,可以订阅主题,打印出收到的消息,然后将更多指令发布到新主题.在订阅/打印在一个够程完成,出版在另一个goroutine中进行.这是我的代码:
var wg, pg sync.WaitGroup
// All messages are handled here - printing published messages and publishing new messages
var f MQTT.MessageHandler = func(client MQTT.Client, msg MQTT.Message) {
wg.Add(1)
pg.Add(1)
go func() {
defer wg.Done()
fmt.Printf("%s\n", msg.Payload())
//fmt.Println(os.Getpid())
}()
go func(){
defer pg.Done()
message := ""
//Changing configurations
if strings.Contains(string(msg.Payload()), "arduinoLED") == true {
message = fmt.Sprintf("change configuration")
}
if strings.Contains(string(msg.Payload()), "NAME CHANGED") == true{
message = fmt.Sprintf("change back")
}
// Publish further instructions to "sensor/instruction" …Run Code Online (Sandbox Code Playgroud)