Multiple goroutines reading from a channel gives wrong data count
I'm working on a program where I read a csv file and do below operations:
Full Code is available at:Here
My CSV file is available at:
CSV file
The problem is sometimes I get the correct count for A and B and sometimes I get the wrong count.
I think I'm doing something wrong in Goroutines and channels communication.
When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
Can anyone please explain what wrong I'm doing?
Also when I do go run -race main.go, the result shows me a race condition.
func main() {
input, err := os.Open("CSV.csv")
if err != nil {
fmt.Println("Error while opening CSV file.")
return
}
defer input.Close()
formattedStartDateRange,err := time.Parse(time.RFC3339, startDateRange)
if err != nil {
fmt.Println(err)
}
formattedendDateRange,err := time.Parse(time.RFC3339, endDateRange)
if err != nil {
fmt.Println(err)
}
reader := csv.NewReader(input)
reader.FieldsPerRecord = -1
files := make(map[string]chan string)
wg := &sync.WaitGroup{}
var line string
for line, err = reader.Read(); err == nil; line, err = reader.Read() {
ch, ok := files[line[0]]
if ok {
ch <- line
} else {
ch = make(chan string, 8)
ch <- line
wg.Add(2) // Must wait for 2 calls to 'done' before moving on
go func() {
UserMapMutex.Lock()
if (findNumberOfBuilds(formattedStartDateRange, formattedendDateRange, ch, wg)) {
totalBuildCount++
}
UserMapMutex.Unlock()
wg.Done()
}()
go func() {
UserMapMutex.Lock()
countUserBuildFrequency(ch, wg)
UserMapMutex.Unlock()
wg.Done()
}()
files[line[0]] = ch
}
}
if err.Error() != "EOF" {
fmt.Println("Error while reading CSV file.")
return
}
for _, ch := range files {
close(ch)
}
wg.Wait()
fmt.Println("Total Build executed from 1st November to 30th November =", totalBuildCount)
fmt.Println("Total Build", userBuildFreq["5c00a8f685db9ec46dbc13d7"])
fmt.Println("Done!")
}
go concurrency goroutine
add a comment |
I'm working on a program where I read a csv file and do below operations:
Full Code is available at:Here
My CSV file is available at:
CSV file
The problem is sometimes I get the correct count for A and B and sometimes I get the wrong count.
I think I'm doing something wrong in Goroutines and channels communication.
When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
Can anyone please explain what wrong I'm doing?
Also when I do go run -race main.go, the result shows me a race condition.
func main() {
input, err := os.Open("CSV.csv")
if err != nil {
fmt.Println("Error while opening CSV file.")
return
}
defer input.Close()
formattedStartDateRange,err := time.Parse(time.RFC3339, startDateRange)
if err != nil {
fmt.Println(err)
}
formattedendDateRange,err := time.Parse(time.RFC3339, endDateRange)
if err != nil {
fmt.Println(err)
}
reader := csv.NewReader(input)
reader.FieldsPerRecord = -1
files := make(map[string]chan string)
wg := &sync.WaitGroup{}
var line string
for line, err = reader.Read(); err == nil; line, err = reader.Read() {
ch, ok := files[line[0]]
if ok {
ch <- line
} else {
ch = make(chan string, 8)
ch <- line
wg.Add(2) // Must wait for 2 calls to 'done' before moving on
go func() {
UserMapMutex.Lock()
if (findNumberOfBuilds(formattedStartDateRange, formattedendDateRange, ch, wg)) {
totalBuildCount++
}
UserMapMutex.Unlock()
wg.Done()
}()
go func() {
UserMapMutex.Lock()
countUserBuildFrequency(ch, wg)
UserMapMutex.Unlock()
wg.Done()
}()
files[line[0]] = ch
}
}
if err.Error() != "EOF" {
fmt.Println("Error while reading CSV file.")
return
}
for _, ch := range files {
close(ch)
}
wg.Wait()
fmt.Println("Total Build executed from 1st November to 30th November =", totalBuildCount)
fmt.Println("Total Build", userBuildFreq["5c00a8f685db9ec46dbc13d7"])
fmt.Println("Done!")
}
go concurrency goroutine
2
All questions must be complete, without the need to follow links. This means you must include a Minimal, Complete, Verifiable Example of your code and CSV file in the question. Providing links to the larger versions is, of course, welcome, but the key is the question must be complete on its own, in case the links die in the future.
– Flimzy
Jan 1 at 11:21
This code is very strange. For each line, you create a goroutine, write a line to a channel, then the goroutines each call a function that uses that channel in some way that is not shown. This a) means that function call may or may not be using the line that was just inserted - you should probably just pass the line instead of using the channel; and b) means that if one of those functions reads a value from the channel, the other won't be able to because that would be twice as many receives as sends; and c) you run two goroutines which are both fully locked so you might as well just use one.
– Adrian
Jan 2 at 15:28
Correct! The B option mentioned by you is what I'm doing. I did the same and used only one goroutine.
– Brainstormer
Jan 2 at 16:37
But got a doubt, how we would achieve the correct result when we have two goroutines? I understand that if one goroutines reads from channel then other won't be able to read. Is there any way of doing it?
– Brainstormer
Jan 2 at 16:39
add a comment |
I'm working on a program where I read a csv file and do below operations:
Full Code is available at:Here
My CSV file is available at:
CSV file
The problem is sometimes I get the correct count for A and B and sometimes I get the wrong count.
I think I'm doing something wrong in Goroutines and channels communication.
When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
Can anyone please explain what wrong I'm doing?
Also when I do go run -race main.go, the result shows me a race condition.
func main() {
input, err := os.Open("CSV.csv")
if err != nil {
fmt.Println("Error while opening CSV file.")
return
}
defer input.Close()
formattedStartDateRange,err := time.Parse(time.RFC3339, startDateRange)
if err != nil {
fmt.Println(err)
}
formattedendDateRange,err := time.Parse(time.RFC3339, endDateRange)
if err != nil {
fmt.Println(err)
}
reader := csv.NewReader(input)
reader.FieldsPerRecord = -1
files := make(map[string]chan string)
wg := &sync.WaitGroup{}
var line string
for line, err = reader.Read(); err == nil; line, err = reader.Read() {
ch, ok := files[line[0]]
if ok {
ch <- line
} else {
ch = make(chan string, 8)
ch <- line
wg.Add(2) // Must wait for 2 calls to 'done' before moving on
go func() {
UserMapMutex.Lock()
if (findNumberOfBuilds(formattedStartDateRange, formattedendDateRange, ch, wg)) {
totalBuildCount++
}
UserMapMutex.Unlock()
wg.Done()
}()
go func() {
UserMapMutex.Lock()
countUserBuildFrequency(ch, wg)
UserMapMutex.Unlock()
wg.Done()
}()
files[line[0]] = ch
}
}
if err.Error() != "EOF" {
fmt.Println("Error while reading CSV file.")
return
}
for _, ch := range files {
close(ch)
}
wg.Wait()
fmt.Println("Total Build executed from 1st November to 30th November =", totalBuildCount)
fmt.Println("Total Build", userBuildFreq["5c00a8f685db9ec46dbc13d7"])
fmt.Println("Done!")
}
go concurrency goroutine
I'm working on a program where I read a csv file and do below operations:
Full Code is available at:Here
My CSV file is available at:
CSV file
The problem is sometimes I get the correct count for A and B and sometimes I get the wrong count.
I think I'm doing something wrong in Goroutines and channels communication.
When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
Can anyone please explain what wrong I'm doing?
Also when I do go run -race main.go, the result shows me a race condition.
func main() {
input, err := os.Open("CSV.csv")
if err != nil {
fmt.Println("Error while opening CSV file.")
return
}
defer input.Close()
formattedStartDateRange,err := time.Parse(time.RFC3339, startDateRange)
if err != nil {
fmt.Println(err)
}
formattedendDateRange,err := time.Parse(time.RFC3339, endDateRange)
if err != nil {
fmt.Println(err)
}
reader := csv.NewReader(input)
reader.FieldsPerRecord = -1
files := make(map[string]chan string)
wg := &sync.WaitGroup{}
var line string
for line, err = reader.Read(); err == nil; line, err = reader.Read() {
ch, ok := files[line[0]]
if ok {
ch <- line
} else {
ch = make(chan string, 8)
ch <- line
wg.Add(2) // Must wait for 2 calls to 'done' before moving on
go func() {
UserMapMutex.Lock()
if (findNumberOfBuilds(formattedStartDateRange, formattedendDateRange, ch, wg)) {
totalBuildCount++
}
UserMapMutex.Unlock()
wg.Done()
}()
go func() {
UserMapMutex.Lock()
countUserBuildFrequency(ch, wg)
UserMapMutex.Unlock()
wg.Done()
}()
files[line[0]] = ch
}
}
if err.Error() != "EOF" {
fmt.Println("Error while reading CSV file.")
return
}
for _, ch := range files {
close(ch)
}
wg.Wait()
fmt.Println("Total Build executed from 1st November to 30th November =", totalBuildCount)
fmt.Println("Total Build", userBuildFreq["5c00a8f685db9ec46dbc13d7"])
fmt.Println("Done!")
}
go concurrency goroutine
go concurrency goroutine
edited Jan 3 at 16:21
Brainstormer
asked Jan 1 at 9:20
BrainstormerBrainstormer
11
11
2
All questions must be complete, without the need to follow links. This means you must include a Minimal, Complete, Verifiable Example of your code and CSV file in the question. Providing links to the larger versions is, of course, welcome, but the key is the question must be complete on its own, in case the links die in the future.
– Flimzy
Jan 1 at 11:21
This code is very strange. For each line, you create a goroutine, write a line to a channel, then the goroutines each call a function that uses that channel in some way that is not shown. This a) means that function call may or may not be using the line that was just inserted - you should probably just pass the line instead of using the channel; and b) means that if one of those functions reads a value from the channel, the other won't be able to because that would be twice as many receives as sends; and c) you run two goroutines which are both fully locked so you might as well just use one.
– Adrian
Jan 2 at 15:28
Correct! The B option mentioned by you is what I'm doing. I did the same and used only one goroutine.
– Brainstormer
Jan 2 at 16:37
But got a doubt, how we would achieve the correct result when we have two goroutines? I understand that if one goroutines reads from channel then other won't be able to read. Is there any way of doing it?
– Brainstormer
Jan 2 at 16:39
add a comment |
2
All questions must be complete, without the need to follow links. This means you must include a Minimal, Complete, Verifiable Example of your code and CSV file in the question. Providing links to the larger versions is, of course, welcome, but the key is the question must be complete on its own, in case the links die in the future.
– Flimzy
Jan 1 at 11:21
This code is very strange. For each line, you create a goroutine, write a line to a channel, then the goroutines each call a function that uses that channel in some way that is not shown. This a) means that function call may or may not be using the line that was just inserted - you should probably just pass the line instead of using the channel; and b) means that if one of those functions reads a value from the channel, the other won't be able to because that would be twice as many receives as sends; and c) you run two goroutines which are both fully locked so you might as well just use one.
– Adrian
Jan 2 at 15:28
Correct! The B option mentioned by you is what I'm doing. I did the same and used only one goroutine.
– Brainstormer
Jan 2 at 16:37
But got a doubt, how we would achieve the correct result when we have two goroutines? I understand that if one goroutines reads from channel then other won't be able to read. Is there any way of doing it?
– Brainstormer
Jan 2 at 16:39
2
2
All questions must be complete, without the need to follow links. This means you must include a Minimal, Complete, Verifiable Example of your code and CSV file in the question. Providing links to the larger versions is, of course, welcome, but the key is the question must be complete on its own, in case the links die in the future.
– Flimzy
Jan 1 at 11:21
All questions must be complete, without the need to follow links. This means you must include a Minimal, Complete, Verifiable Example of your code and CSV file in the question. Providing links to the larger versions is, of course, welcome, but the key is the question must be complete on its own, in case the links die in the future.
– Flimzy
Jan 1 at 11:21
This code is very strange. For each line, you create a goroutine, write a line to a channel, then the goroutines each call a function that uses that channel in some way that is not shown. This a) means that function call may or may not be using the line that was just inserted - you should probably just pass the line instead of using the channel; and b) means that if one of those functions reads a value from the channel, the other won't be able to because that would be twice as many receives as sends; and c) you run two goroutines which are both fully locked so you might as well just use one.
– Adrian
Jan 2 at 15:28
This code is very strange. For each line, you create a goroutine, write a line to a channel, then the goroutines each call a function that uses that channel in some way that is not shown. This a) means that function call may or may not be using the line that was just inserted - you should probably just pass the line instead of using the channel; and b) means that if one of those functions reads a value from the channel, the other won't be able to because that would be twice as many receives as sends; and c) you run two goroutines which are both fully locked so you might as well just use one.
– Adrian
Jan 2 at 15:28
Correct! The B option mentioned by you is what I'm doing. I did the same and used only one goroutine.
– Brainstormer
Jan 2 at 16:37
Correct! The B option mentioned by you is what I'm doing. I did the same and used only one goroutine.
– Brainstormer
Jan 2 at 16:37
But got a doubt, how we would achieve the correct result when we have two goroutines? I understand that if one goroutines reads from channel then other won't be able to read. Is there any way of doing it?
– Brainstormer
Jan 2 at 16:39
But got a doubt, how we would achieve the correct result when we have two goroutines? I understand that if one goroutines reads from channel then other won't be able to read. Is there any way of doing it?
– Brainstormer
Jan 2 at 16:39
add a comment |
1 Answer
1
active
oldest
votes
In both cases, your wg.Done() is being called immediately after you start the goroutine. This means that your WaitGroup is not waiting for the goroutine to finish. Remember that the calling process proceeds when you call a goroutine. Try putting the wg.Done() call inside the goroutine, when it's finished doing stuff.
go func(wg) {
// do stuff
wg.Done
}
OR
go func(wg) {
defer wg.Done
// do stuff
}
I have update the code as you have said in the below link play.golang.org/p/8Mhjco_7RyM But still it doesn't work out. When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
– Brainstormer
Jan 1 at 20:20
So I think it is 2nd Goroutine which is creating the mess.
– Brainstormer
Jan 1 at 20:26
Do you find anything new?
– Brainstormer
Jan 2 at 8:45
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994299%2fmultiple-goroutines-reading-from-a-channel-gives-wrong-data-count%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
In both cases, your wg.Done() is being called immediately after you start the goroutine. This means that your WaitGroup is not waiting for the goroutine to finish. Remember that the calling process proceeds when you call a goroutine. Try putting the wg.Done() call inside the goroutine, when it's finished doing stuff.
go func(wg) {
// do stuff
wg.Done
}
OR
go func(wg) {
defer wg.Done
// do stuff
}
I have update the code as you have said in the below link play.golang.org/p/8Mhjco_7RyM But still it doesn't work out. When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
– Brainstormer
Jan 1 at 20:20
So I think it is 2nd Goroutine which is creating the mess.
– Brainstormer
Jan 1 at 20:26
Do you find anything new?
– Brainstormer
Jan 2 at 8:45
add a comment |
In both cases, your wg.Done() is being called immediately after you start the goroutine. This means that your WaitGroup is not waiting for the goroutine to finish. Remember that the calling process proceeds when you call a goroutine. Try putting the wg.Done() call inside the goroutine, when it's finished doing stuff.
go func(wg) {
// do stuff
wg.Done
}
OR
go func(wg) {
defer wg.Done
// do stuff
}
I have update the code as you have said in the below link play.golang.org/p/8Mhjco_7RyM But still it doesn't work out. When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
– Brainstormer
Jan 1 at 20:20
So I think it is 2nd Goroutine which is creating the mess.
– Brainstormer
Jan 1 at 20:26
Do you find anything new?
– Brainstormer
Jan 2 at 8:45
add a comment |
In both cases, your wg.Done() is being called immediately after you start the goroutine. This means that your WaitGroup is not waiting for the goroutine to finish. Remember that the calling process proceeds when you call a goroutine. Try putting the wg.Done() call inside the goroutine, when it's finished doing stuff.
go func(wg) {
// do stuff
wg.Done
}
OR
go func(wg) {
defer wg.Done
// do stuff
}
In both cases, your wg.Done() is being called immediately after you start the goroutine. This means that your WaitGroup is not waiting for the goroutine to finish. Remember that the calling process proceeds when you call a goroutine. Try putting the wg.Done() call inside the goroutine, when it's finished doing stuff.
go func(wg) {
// do stuff
wg.Done
}
OR
go func(wg) {
defer wg.Done
// do stuff
}
answered Jan 1 at 10:21
blobdonblobdon
57238
57238
I have update the code as you have said in the below link play.golang.org/p/8Mhjco_7RyM But still it doesn't work out. When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
– Brainstormer
Jan 1 at 20:20
So I think it is 2nd Goroutine which is creating the mess.
– Brainstormer
Jan 1 at 20:26
Do you find anything new?
– Brainstormer
Jan 2 at 8:45
add a comment |
I have update the code as you have said in the below link play.golang.org/p/8Mhjco_7RyM But still it doesn't work out. When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
– Brainstormer
Jan 1 at 20:20
So I think it is 2nd Goroutine which is creating the mess.
– Brainstormer
Jan 1 at 20:26
Do you find anything new?
– Brainstormer
Jan 2 at 8:45
I have update the code as you have said in the below link play.golang.org/p/8Mhjco_7RyM But still it doesn't work out. When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
– Brainstormer
Jan 1 at 20:20
I have update the code as you have said in the below link play.golang.org/p/8Mhjco_7RyM But still it doesn't work out. When I comment the 2nd goroutine, I get correct result of 1st Goroutine. But when I uncomment 2nd Goroutine, I get incorrect output of Goroutine 1 and 2 both.
– Brainstormer
Jan 1 at 20:20
So I think it is 2nd Goroutine which is creating the mess.
– Brainstormer
Jan 1 at 20:26
So I think it is 2nd Goroutine which is creating the mess.
– Brainstormer
Jan 1 at 20:26
Do you find anything new?
– Brainstormer
Jan 2 at 8:45
Do you find anything new?
– Brainstormer
Jan 2 at 8:45
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53994299%2fmultiple-goroutines-reading-from-a-channel-gives-wrong-data-count%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
2
All questions must be complete, without the need to follow links. This means you must include a Minimal, Complete, Verifiable Example of your code and CSV file in the question. Providing links to the larger versions is, of course, welcome, but the key is the question must be complete on its own, in case the links die in the future.
– Flimzy
Jan 1 at 11:21
This code is very strange. For each line, you create a goroutine, write a line to a channel, then the goroutines each call a function that uses that channel in some way that is not shown. This a) means that function call may or may not be using the line that was just inserted - you should probably just pass the line instead of using the channel; and b) means that if one of those functions reads a value from the channel, the other won't be able to because that would be twice as many receives as sends; and c) you run two goroutines which are both fully locked so you might as well just use one.
– Adrian
Jan 2 at 15:28
Correct! The B option mentioned by you is what I'm doing. I did the same and used only one goroutine.
– Brainstormer
Jan 2 at 16:37
But got a doubt, how we would achieve the correct result when we have two goroutines? I understand that if one goroutines reads from channel then other won't be able to read. Is there any way of doing it?
– Brainstormer
Jan 2 at 16:39