美文网首页
golang并发处理示例

golang并发处理示例

作者: mihope | 来源:发表于2019-02-28 13:50 被阅读0次
package main

import (
    "flag"
    "fmt"
    "strconv"
)

var count *int

func init() {
    count = flag.Int("num", 22, "计算素数")
}

func main() {
    flag.Parse()
    origin, wait := make(chan int), make(chan struct{})
    Processor(origin, wait)
    for num := 2; num < *count; num++ {
        origin <- num
    }
    close(origin)
    <-wait
}

func Processor(seq chan int, wait chan struct{}) {
    go func() {
        prime, ok := <-seq
        if !ok {
            close(wait)
            return
        }
        fmt.Println(prime)
        out := make(chan int)
        Processor(out, wait)
        for num := range seq {
            fmt.Println("write " +strconv.Itoa(num)+"==%="+strconv.Itoa(prime))
            if num%prime != 0 {
                out <- num
            }
        }
        close(out)
    }()
}

package main

import (
    "context"
    "fmt"
    "net/http"
    "time"
)

func Proc(ctx context.Context) {
    for {
        select {
        case <-ctx.Done():
            fmt.Println("hhhh")
            return
        default:
            fmt.Println("---")
        }
    }
}
//取消
func main() {
    ctx := context.Background()
    ctx, cancel := context.WithCancel(ctx)
    go Proc(ctx)
    go Proc(ctx)
    go Proc(ctx)
    time.Sleep(2 * time.Millisecond)
    cancel()
}
//超时
func Handler(r *http.Request) {
    ctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancelFunc()
    done := make(chan struct{}, 1)
    go func() {
        RPC(ctx, "data")
        done <- struct{}{}
    }()
    select {
    case <-done:
        //nice
    case <-ctx.Done():
        //timeout
    }
}

func RPC(ctx context.Context, s string) {

}

相关文章

网友评论

      本文标题:golang并发处理示例

      本文链接:https://www.haomeiwen.com/subject/bxmhuqtx.html