When I want to keep track of active connections, is it better to save them into linked list or directly to some array where index will represent ID of the connection? I want to prevent possible race condition issues, for example:
- number of connections in the list is big
- someone start to search for a connection which is at the end of the list
- meanwhile, du开发者_JS百科ring the search, the connection is detached
The structure should have a connection handle (SOCKET), a reference count, and a flag denoting that connection should be closed and the object deleted as soon as possible. Whatever the container is it must have synchronization mechanism (critical section) for search/insert/remove, and GetReference/Release logic. GetReference function should return NULL if closing flag is raised. You might need more that one GetReference, depending on search conditions (and connection object should have all those values that can help it being found in container). One of GetReference functions can create new object if it does not exist in container.
Release function should close the connection and delete the object from container if closing flag is raised and reference count is dropped to zero. However Release must not close the connection within critical section, because that can be time consuming operation (depends on graceful shutdown and lingering option). Release should enter CS, decrease reference count, if it is zero then leave CS, close connection, enter CS again, and remove object from container and delete it. Because the closing flag is raised the reference count will not raise between two CS's.
精彩评论