checkmate
checkmate

Reputation: 267

Go lang multi waitgroup and timer stops in the end

i have written the following code in order to run until someone exit the program manually.

it does is

for this i have first call a function from the main and then i call a waitgroup and call a function again from there to do the aforementioned tasks.

please check if i have written the source code correctly as im a newbi on GO

plus this only runs once and stop... i want to it keep alive and see if the file exsists

please help me

 package main

import (
    "encoding/csv"
    "fmt"
    "io"
    "log"
    "os"
    "sync"
    "time"
)

func main() {
    mainfunction()
}

//------------------------------------------------------------------

func mainfunction() {
    var wg sync.WaitGroup
    wg.Add(1)

    go filecheck(&wg)

    wg.Wait()
    fmt.Printf("Program finished \n")

}

func filecheck(wg *sync.WaitGroup) {

    for range time.Tick(time.Second * 1) {
        fmt.Println("Foo")

        var wgi sync.WaitGroup
        wgi.Add(1)

        oldName := "test.csv"
        newName := "testi.csv"

        if _, err := os.Stat(oldName); os.IsNotExist(err) {
            fmt.Printf("Path does not exsist \n")
        } else {
            os.Rename(oldName, newName)
            if err != nil {
                log.Fatal(err)
            }
            looping(newName, &wgi)
        }
        fmt.Printf("Test complete \n")
        wgi.Wait()
        wg.Done()
        time.Sleep(time.Second * 5)
    }
}

func looping(newName string, wgi *sync.WaitGroup) {
    file, _ := os.Open(newName)
    r := csv.NewReader(file)
    for {
        record, err := r.Read()
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }

        var Date = record[0]
        var Agent = record[1]
        var Srcip = record[2]
        var Level = record[3]

        fmt.Printf("Data: %s Agent: %s Srcip: %s Level: %s\n", Date, Agent, Srcip, Level)
    }
    fmt.Printf("Test complete 2 \n")
    wgi.Done()

    fmt.Printf("for ended")
}

Upvotes: 0

Views: 44

Answers (1)

Eli Bendersky
Eli Bendersky

Reputation: 273854

The short answer is that you have this in the loop:

    wg.Done()

Which makes the main goroutine proceed to exit as soon as the file is read once.


The longer answer is that you're not using wait groups correctly here, IMHO. For example there's absolutely no point in passing a WaitGroup into looping.

It's not clear what your code is trying to accomplish - you certainly don't need any goroutines to just perform the task you've specified - it can all be gone with no concurrency and thus simpler code.

Upvotes: 2

Related Questions