↓ Skip to main content
Go

Race condition

·1 min
Table of Contents

When two processes are executing concurrently, the exact order of execution of instructions is not deterministic. Without explicit synchronization instructions it is difficult to predict the outcome of these concurrent execution of process.

Example 1
#

package main

import "fmt"

func secondFunction() {
  fmt.Println(" Second Function")
}

func main() {
  go secondFunction()
  fmt.Print(" Main function")
}

As evident in the example above, we define a GO module secondFunction that is called as the first instruction of the main routine.

In some conditions the line “Second Function” should appear immediately before “ Main Function” and in some cases only the “ Main function” gets printed.

There is no sure shot way of knowing what will be the exact outcome of the execution. This is due to the race condition, where the CPU cycles are shared between the two threads (interleavings of instructions)

Example 2
#

package main

import "fmt"

func secondFunction() {
    fmt.Println(" Second Function")
}

func thirdFunction() {
    fmt.Println(" Third Function")
}

func main() {
    go secondFunction()
    fmt.Print(" Main function\n")
    go thirdFunction()
}

 tried execution three times as evident in the output below.

Terminal running go run week2/week2.go three times with different output each run, showing the race condition

You can see the different output each time, which displays the race condition aptly, as we can never be sure of what will be the output each time.

Author
Samarthya
Engineer, learner, tinkerer. This is my trophy shelf of everyday work and leisure.

Related

Package String

Just like Java or C++ there are standard libraries (packages) available with golang. The one that you might end up using the most often is strings. For this blog, I was writing another practice exercise that is meant to count number of words in an input string.

Dockeriz'd service

·4 mins
Someone asked me to define a simple docker pod for the service I wrote in GOLang here. I completely forgot about it, till today. So here is my first attempt at getting a docker image for the service.