For last 48 hours, I have been trying to understand Multithreading
and Socket Programming
. I tried to implement socket programming and had success when not using multithreading. I am new to both of the topics and have raised 2-3 question on stack itself needing help on the same.
After googling a lot I found an article that explains Socket Programming
and Multithreading
, but I still have a lot of doubts in this article and got stuck at Figure 5
in the article.
private void AcceptConnections()
{
while (true)
{
// Accept a connection
Socket socket = _serverSocket.Accept();
ConnectionInfo connection = new ConnectionInfo();
connection.Socket = socket;
// Create the thread for the receives.
connection.Thread = new Thread(ProcessConnection);
connection.Thread.IsBackground = true;
connection.Thread.Start(connection);
// Store the socket
lock (_connections) _connections.Add(connection);
}
}
In the very last line you can see a lock
has been taken and 3-4 lines above a delegate ProcessConnection
is bound.
At this point, I am not clear how this lock is working. What is happening behind the scenes when the lock has taken? Why did the author use lock here? What would have happened if no lock was taken? How does the thread ProcessConnection work? What things are happening simultaneously?
I got confused with all these questions
I know there is a list of questions here, but it would be a great help if you could assist me in understanding the methodology of working with multithreading.