<jupyter_start><jupyter_text>Concurrency and races Below is an example of code with data races. Data Races occur when there is at least one read and another write at the same location. Consider the following example<jupyter_code>func dataRaceExample() {
    var count = 0
    
    func inc() {
        if count == 0 {
            count++
        }
    }
    
    func main() {
        go inc()
        go inc()
        time.Sleep(1 * time.Millisecond)
    }
    main()
}

dataRaceExample()<jupyter_output><empty_output><jupyter_text>Data race is pretty obvious at `count++` since multiple user-threads read and write to it simultaenouslyAn improved version may look like this. Look under `concurrency/` directory for `go` code<jupyter_code>import (
	"context"
	"fmt"
	"sync"
	"time"
)

var (
	count = 0
	wg    sync.WaitGroup
	m     = sync.Mutex{}
)

func incrementCount(ctx context.Context, who string) {
	defer wg.Done()

	inc := 0
	for {
		select {
		case <-ctx.Done():
			fmt.Println(who, inc, " ... exiting")
			return
		case <-time.After(400 * time.Millisecond):
			inc += 1
			m.Lock()    // <<< sync access to data
			fmt.Println(who, inc, ":   now  :", count)
			count += 1
			fmt.Println(who, inc, ":   inc  :", count)
			m.Unlock()  // <<< end of sync block
		}
	}
}

func cancel() {
	fmt.Println(" .... cancel")
}

func main() {

	ctx, cancel := context.WithCancel(context.Background())

	wg.Add(3)
	go incrementCount(ctx, "A")
	go incrementCount(ctx, "                     B")
	go incrementCount(ctx, "                                           C")

	time.AfterFunc(3*time.Second, cancel)
	wg.Wait()

	fmt.Println("  ... end: ", count)   
}

main()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.13313609467455623, 'fraction_numerical': 0.007100591715976331, 'mean_word_length': 2.508298755186722, 'pattern_counts': {'":': 2, '<': 17, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 2, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '2', 'dir': 'jupyter-structured-clean-dedup', 'id': '396467', 'license': 'MIT', 'n_tokens_mistral': 609, 'n_tokens_neox': 564, 'n_words': 160, 'path': 'go/lang/concurrency-races.ipynb', 'repo_name': 'sthaha/notes', 'size': '1690'}