Skip to content

Instantly share code, notes, and snippets.

@ehfeng
Last active December 8, 2022 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehfeng/d686d26679cad6973f8961b0925cc707 to your computer and use it in GitHub Desktop.
Save ehfeng/d686d26679cad6973f8961b0925cc707 to your computer and use it in GitHub Desktop.
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