Skip to content

Instantly share code, notes, and snippets.

@kartikx
Created January 14, 2021 05:25
Show Gist options
  • Save kartikx/7ff31e30cf413161a0d6a46e8f3ac3fe to your computer and use it in GitHub Desktop.
Save kartikx/7ff31e30cf413161a0d6a46e8f3ac3fe to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"os"
"strconv"
"sync"
"time"
)
var wg sync.WaitGroup
var mut sync.Mutex
func Writer(file *os.File) {
enc := json.NewEncoder(file)
for i := 0; i < 5; i++ {
fmt.Println("Writer")
// mut.Lock()
enc.Encode("Line" + strconv.Itoa(i))
// mut.Unlock()
time.Sleep(500 * time.Millisecond)
}
wg.Done()
}
func Reader(file *os.File) {
enc := json.NewDecoder(file)
var str string
for i := 0; i < 5; i++ {
fmt.Println("Reader")
// mut.Lock()
enc.Decode(&str)
// mut.Unlock()
fmt.Println(str)
time.Sleep(500 * time.Millisecond)
}
wg.Done()
}
func main() {
wg.Add(2)
file1, _ := os.Create("test.txt")
file2, _ := os.Open("test.txt")
go Writer(file1)
// Need to ensure that Reader starts reading only after atleast one line has been written.
time.Sleep(500 * time.Millisecond)
go Reader(file2)
wg.Wait()
}
@kartikx
Copy link
Author

kartikx commented Jan 14, 2021

For some reason if Reader starts reading before Writer has written the first line, then the Reader is never able to read any lines at all. Even if Writer manages to catch up and write more lines than the Reader has currently read.
To understand this I may need to properly understand how the encoding/json package reads from files. It probably keeps incrementing SEEK_CUR (or equivalent) which makes Reader unable to read anything if it starts first, but that doesn't explain why it doesn't read anything even when writer has eventually moved forward.
Maybe they somehow end up working on different files?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment