How to use multithreading, locking, socket programming

Over the last 48 hours, I tried to understand Multithreadingand Socket Programming. I tried to implement socket programming and was successful when not using multithreading. I am new to both topics and raised 2-3 questions that the stack itself needs help on the same.

After a multiplayer game, I found an article that explains and , but I still have a lot of doubt in this article and got stuck in the article. Socket ProgrammingMultithreadingFigure 5

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 last line you see what has been done lock, and 3-4 rows are tied above delegate ProcessConnection.

, . ? ? , ? ProcessConnection? ?

, , , .

+1
3

connection.Thread.Start(connection) ProcessConnection, connection state. , ProcessConnection .

ProcessConnection Socket ConnectionInfo, AcceptConnections, . , ConnectionInfo connections .

, ? , ( Thread 0), AcceptConnections . , , , ProcessConnection.

, ProcessConnection foreach . Thread 0 , foreach, InvalidOperationException ProcessConnection.

lock concurrency , . AcceptConnections , ProcessConnection . , ProcessConnection, . ReaderWriterLockSlim, .

+2

, _connections - List<ConnectionInfo>: , . , . , , .

connection.Thread.Start(connection); , . (, ) . ConnectionInfo , , . , ProcessConnection .

+1

In C #, and I think in the CLR in general, every object can have a monitor associated with it. Here _connectionsis a collection that is possibly shared by threads running from this function itself (they will probably remove connections from the collection when they are complete). Collections in C # are not synchronized by default, you must do this explicitly, so the operator lock(_connections)is to prevent races in collections.

+1
source

Source: https://habr.com/ru/post/1756117/


All Articles