Last active
December 8, 2022 06:16
-
-
Save ehfeng/d686d26679cad6973f8961b0925cc707 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"strconv" | |
"time" | |
v8 "rogchap.com/v8go" | |
) | |
func concurrency(ctx context.Context, workers int, c chan string, d chan string) { | |
for i := 0; i < workers; i++ { | |
i := i | |
go func() { | |
fmt.Println("starting") | |
iso := v8.NewIsolate() | |
v8Ctx := v8.NewContext(iso) | |
for { | |
select { | |
case s := <-c: | |
fmt.Println("received", s, "from worker", i) | |
v, err := v8Ctx.RunScript(s, "") | |
if err != nil { | |
panic(err) | |
} | |
d <- v.String() + "from strong" + strconv.Itoa(i) | |
iso.Dispose() | |
iso = v8.NewIsolate() | |
v8Ctx = v8.NewContext(iso) | |
case <-ctx.Done(): | |
fmt.Println("received done", ctx.Err()) | |
return | |
} | |
} | |
}() | |
} | |
} | |
func main() { | |
workers := 4 | |
c := make(chan string, workers) | |
d := make(chan string, workers) | |
ctx, cancelFunc := context.WithCancel(context.Background()) | |
concurrency(ctx, workers, c, d) | |
go func() { | |
for { | |
c <- "100+11" | |
time.Sleep(time.Second) | |
} | |
}() | |
go func() { | |
time.Sleep(time.Second * 4) | |
cancelFunc() | |
close(d) | |
fmt.Println("called cancel") | |
}() | |
for e := range d { | |
fmt.Println("result", e) | |
} | |
fmt.Println("ending:", ctx.Err()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment