M
M
markinaras2022-01-12 17:51:13
go
markinaras, 2022-01-12 17:51:13

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


Result:
str:a2 [a2]
str:a1 [a1]
str:a5 [a1 a5]
str:a3 [a1 a5 a3]
str:a4 [a1 a5 a3 a4]

Need to be:
str:a2 [a2]
str :a1 [a1]
str:a5 [a5]
str:a3 [a3]
str:a4 [a4]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2022-01-12
@markinaras

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 question

Ask a Question

731 491 924 answers to any question