Goroutine behaves differently on Windows and Linux

Issue

I`m new to the GO. I have a following legacy code.

var db *sql.DB

func init() {
    go feedChan()

    connString := os.Getenv("DB_CONN")
    var err error

    db, err = sql.Open("postgres", connString)
    if err != nil {
        log.Fatalf("Failed to connect to database at %q: %q\n", connString, err)
    }

    // confirm connection
    if err = db.Ping(); err != nil {
        log.Fatalf("Unable to ping database at %q: %q\n", connString, err)
    }
}


func feedChan() {
    selectQuery, err := db.Prepare(`
        SELECT id, proxy
        FROM proxy
        WHERE fail_count < 2
        ORDER BY date_added DESC, last_used ASC, fail_count ASC
        LIMIT 5
    `)
    ....

Following code works on linux. But it fails on windows with nil error on

selectQuery, err := db.Prepare(`

Which make sense for me, since db initialized after a launch of feedChan goroutine. What doesnt make sense for me is why it work on linux.

So the question is why this code work at linux without errors?

Solution

That’s probably a race condition. Import "time", put this line after go feedChan(), and see if it still works on Linux:

time.Sleep(3 * time.Second)

In order to avoid this situation, you could either initialize db before you spawn the routine (which uses db) or use some sort of barrier:

func init() {
    barrier := make(chan int)
    go feedChan(barrier)

    connString := os.Getenv("DB_CONN")
    var err error
    db, err = sql.Open("postgres", connString)

    if err != nil {
        log.Fatalf("Failed to connect to database at %q: %q\n", connString, err)
        // Retry.
    } else {
        barrier <- 1 // Opens barrier.
    }
    // ...
}


func feedChan(barrier chan int) {
    <-barrier // Blocks until db is ready.
    selectQuery, err := db.Prepare(`
        SELECT id, proxy
        FROM proxy
        WHERE fail_count < 2
        ORDER BY date_added DESC, last_used ASC, fail_count ASC
        LIMIT 5
    `)
    // ...
}

Answered By – beatngu13

Answer Checked By – Marie Seifert (GoLangFix Admin)

Leave a Reply

Your email address will not be published.