I develop the server in C# and have a question:
Let's say I have the List <Socket>
, it have 20 objects, from the first object (socket) comes a message that I must:
- duplicate to all objects in the worksheet
or
- duplicate to one particular object
Everything works correctly, if it is currently work one thread with List <Socket>
.
But if to List <Socket>
suddenly turn 20 threads simultaneously (message arrived from everyone), which not only pass on the List and send a message, but also on the basis of the contents of the messages can close the socket and remove it from the List, then I do not know how to create atomic access and not lose productivity.
String targetIp, msg;
lock(socketListMutex)
{
for(int i = 0; i < listSocket.Count; ++i)
{
if(listSocket.elementAt(i).targetIp == targetIp)
{
listSocket.sendTo(msg);
break;
}
}
}
Edit 1:
What can happen:
- One of the 20 falls off.
- The list is removed fallen off the socket, and it was in the beginning. As a consequence - the list has shifted to the left.
- At this time all of the sent message and stood in the middle of the cycle. As a result - missed one socket.