-1

My code is little complex, but in simple terms it is having multiple go routines, all dial-ing different tcp server and reading the input in a for loop when a readable message is present over the stream. So far so good. Now there is another go routine which manages the previous bunch of 'clients' and closes them when user wants to. For that I have associated each 'conn' with appropriate go routine client and closing that.

The problem what I am facing is as soon as I call the close function of any conn object, its' corresponding Read function goes in an infinite loop reading just the empty strings continuously.

I wrote a simple code which is similar to the way I am handling the connections in multiple go routines- https://play.golang.org/p/wq7zt9Kqz7

TL;DR

In short I have a 'class' which represents one remote server with its address, conn, waitgroup with in it and I am creating its multiple instances and handling for their inputs in separate go routines. And in another go routine I am trying to close one of those instance and this read() goes in a loop indefinitely.

darthvading
  • 909
  • 2
  • 11
  • 25
  • are you closing the waitgroup correctly (I'm asking because the sample code doesn't say anything about it) Also the sample code doesn't document if you are closing the subroutines correctly. – Fallen Feb 11 '17 at 07:26

2 Answers2

1

Read on a closed connection returns an error.

The application should break out of the read loop on any error returned from Read on the TCP connection. Break on error handles all of these cases: application closes connection in another goroutine, peer shuts down the connection, network error.

No other synchronization is required to coordinate between a closer of a TCP connection and a reader on that connection.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242
0

I think you should use semaphores(channels,select inside method), so, when you call stop, it will send a message(boolean or int), and when method get message from this channel, it will close connection and stop the go rutine.

Short example

select{
case <- stopChannel:
//Do stuff to close connection
case default:
//Do stuff to read from connection
 }

More example you can find there Stackoverflow

B.Zamalutdinov
  • 33
  • 1
  • 1
  • 5
  • Channels were my first choice, but problem I had wanted me to create the instance of "remote server" dynamically, which I couldn't figure out how to do with channels. In case of wait group, I easily used the wg.Add(1) in the loop every time I get a request of a new server. – darthvading Feb 11 '17 at 11:14