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) {
}