Answer the question
In order to leave comments, you need to log in
How to create a package-scoped variable so that other goroutines are not seen and without blocking them?
There are two packages. In the first (main) I run n-number of goroutines. Goroutines work with the second package, where there is a shared visibility variable, and although the goroutines are not connected to each other in any way by the second package, they use this variable as a common one. How can I avoid this without using blocking?
package main
import (
"sync"
"pkg2"
)
var wg sync.WaitGroup
func main() {
text:=[]string{"a1","a2","a3","a4","a5"}
for i,str:=range text{
wg.Add(1)
go start(str)
}
wg.Wait()
}
func start(str string){
pkg2.Test(str)
wg.Done()
}
package pkg2
import "fmt"
var str2 []string // Переменная которую видят все горутины
func Test(str string){
str2=append(str2,str)
fmt.Printf("str:%v %v \n",str,str2)
}
Answer the question
In order to leave comments, you need to log in
You can do something like this.
The implementation is not very beautiful, but I think it will give you an idea in which direction you can move.
package pkg2
import "fmt"
type Pkg2 struct {
str2 []string
}
func New() *Pkg2 {
return &Pkg2{
str2: []string{},
}
}
func (p *Pkg2) Test(str string){
p.str2 = append(p.str2, str)
fmt.Printf("str:%v %v \n", str, p.str2)
}
package main
import (
"sync"
"pkg2"
)
var wg sync.WaitGroup
func main() {
text:=[]string{"a1", "a2", "a3", "a4", "a5"}
for i,str:=range text{
wg.Add(1)
p := pkg2.New()
go start(str, p)
}
wg.Wait()
}
func start(str string, p *pkg2.Pkg2){
p.Test(str)
wg.Done()
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question