Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Golang assignment 8 #6

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open

Golang assignment 8 #6

wants to merge 12 commits into from

Conversation

divyatambat
Copy link
Owner

In the below code snippet concurrent goroutines execution corrupts a piece of data by accessing it simultaneously it leads in raise condition.

Code snippet output when you run this : 1 is Even
Solution snipped output once code is corrected: 0 is Even

Snippets are available in the doc attached below

package main

import (
"fmt"
"time"
)

func isEven(n int) bool {
return n%2 == 0
}

func main() {
n := 0

go func() {
	nIsEven := isEven(n)
	time.Sleep(5 * time.Millisecond)
	if nIsEven {
		fmt.Println(n, " is even")
		return
	}
	fmt.Println(n, "is odd")
}()

go func() {
	n++
}()

// just waiting for the goroutines to finish before exiting
time.Sleep(time.Second)

}

@divyatambat divyatambat requested a review from yama11299 January 25, 2024 11:29
Asg0.8.go Outdated
@@ -5,29 +5,29 @@ import (
"sync"
)

func isEven(n int) bool {
return n%2 == 0
func isEven(n int, m *sync.Mutex) bool {
Copy link
Collaborator

@yama11299 yama11299 Feb 4, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of passing mutex as param and calling Lock here, keep it at caller go-routine. passing it here doesn't solves the original issue. sorry, didn't realize this earlier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants