Hi,
I have created a multi threaded socket server. But it is not behaving like one..
See the following code
In the thread function..Code:/*Creating a Mutex*/ hSocketMutex = CreateMutex( NULL, FALSE, "SocketMutex" ); printf("%s: waiting for data on port TCP %u\n",module,SERVER_PORT); for(;;) { cliLen = sizeof(sdstruct.cliAddr); sdstruct.newSd = accept(sdstruct.sd, (struct sockaddr *) &sdstruct.cliAddr, &cliLen); if(sdstruct.newSd<0) { perror("cannot accept connection "); return 0; } /*Once a client requests I pass that socket structure to the Thread function which will handle that client request*/ hSock = CreateThread (NULL, 0,AcceptConnection, (LPVOID)&sdstruct, 0, &dwThreadId); }
Since I am using a Mutex though the client requested is accepted, it is served after the previous thread releases the Mutex.Code:DWORD WINAPI AcceptConnection(LPVOID lsock) { DWORD iRetVal; SOCKET_STRUCT psock; hSocketMutex= OpenMutex( SYNCHRONIZE, FALSE, "SocketMutex" ); iRetVal = WaitForSingleObject(hSocketMutex, INFINITE ); if( iRetVal == WAIT_FAILED ) { printf("WAIT_FAILED\n"); return 0; } else if( iRetVal == WAIT_TIMEOUT ) { printf("WAIT_TIMEOUT\n"); return 0; } else if( iRetVal == WAIT_OBJECT_0 ) { printf("WAIT_OBJECT_0\n"); } psock = (SOCKET_STRUCT)lsock; memset(args,0,COM_ARGS); if(GetParams(args,psock.newSd)>0) { strcpy(com_dat,args); printf("%d\n",psock.newSd); printf("%s: received from %s:TCP%d : %s\n\n", module,inet_ntoa(sdstruct.cliAddr.sin_addr),ntohs(sdstruct.cliAddr.sin_port), args); memset(args,0,COM_ARGS); ProcessData(psock.newSd); } /*else { printf("Command not received\n"); }*/ ReleaseMutex(hSocketMutex); CloseHandle(hSocketMutex); return 1; }
All I want to know is how to overcome this.
If I dont create the mutex lock then there will be a clash of local/global variables..
Please let me know If there is a better method.
Thanks,
Pradeep




Reply With Quote