• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Laval B

IO completion port

9 posts in this topic

Hello everyone

I have started working on a server project. The server is being developped in C++ and will have to work on Windows and eventually on Solaris but we're focusing on Windows for now.

The server is basically some sort of proxy server that will use a home protocol to provide access to the data (database and file transfer) for applications. It will have to service a few hundreds clients.

I have read that, in order to scale, we should use asynchronous I/O. On windows platform, it means using I/O completion. For what i understant about it, evey time the server receives a connection it registers it to an I/O completion port "object". Then you can have a certain number of threads sitting on calls to [color=#333333][size=3][left]GetQueuedCompletionStatus which will wake the threads when an I/O operation completes. I am wrong ?[/left][/size][/color]

[color=#333333][size=3][left]So, i will need a pool of threads to manage the I/O completion operations. I will likely need another pool to process the queries in order to keep the I/O from blocking for too long,[/left][/size][/color]

[color=#333333][size=3][left]I was looking at the Win32 threadpool api. At a first glance, it doesn't seem too bad but is it really something i should use ? It seems like the threadpool api is also capable of handling I/O completion.[/left][/size][/color]

[color=#333333][size=3][left]Also, does anyone have a good reference on I/O completion port ?[/left][/size][/color]
1

Share this post


Link to post
Share on other sites
I have some example IOCP code that you could download to play with. It provides some classes which wrap up the complexity somewhat. You can get the code from here: [url="http://www.serverframework.com/products---the-free-framework.html"]http://www.serverframework.com/products---the-free-framework.html[/url] There are also links to the code project articles that I wrote about this code back in 2002.
2

Share this post


Link to post
Share on other sites
[quote name='Len Holgate' timestamp='1337355037' post='4941198']
I have some example IOCP code that you could download to play with. It provides some classes which wrap up the complexity somewhat. You can get the code from here: [url="http://www.serverframework.com/products---the-free-framework.html"]http://www.serverfra...-framework.html[/url] There are also links to the code project articles that I wrote about this code back in 2002.
[/quote]

Thank you very much. I'll take a look at it. Iocp can be a bit confusing when you look at it for the fist time.
0

Share this post


Link to post
Share on other sites
Perhaps I'm just lazy. It sounds like you're building something that produces results that are awfully close to what you'd get from a web service like SOAP, so why not just throw a copy of Apache and gSOAP or Axis2 onto your server and be done with it? Most decent RDBMSs include a C/C++ API, so there you go... a fairly secure middle tier up and running in less than a day, and you still get to maintain control at the source code level.

Yes, I know that socket programming can be extremely fun (challenging, rewarding), but I just thought I'd throw the web services route out there. I've done this before with Apache/gSOAP/MySQL Community Edition, and it all worked out extremely well.

P.S. Regarding binary data transfer: "Apache Axis2 supports [b]Base64 encoding[/b], [b]SOAP with Attachments[/b] and [b]MTOM (SOAP Message Transmission Optimization Mechanism)."[/b] Edited by taby
0

Share this post


Link to post
Share on other sites
[quote name='Laval B' timestamp='1337355349' post='4941201']
Thank you very much. I'll take a look at it. Iocp can be a bit confusing when you look at it for the fist time.
[/quote]

Yes, it can, but it's actually fairly straight forward once you get your head around the concept. Remaining async throughout your data processing is the more complex part but that's not too bad if you just build state machines.

The code that I linked to is stable and reliable but it is missing quite a few features that you probably should think about, especially if your server will be sending 'push' notifications to clients that may be on slow network links. I talk about the issues that you can come up against if you ignore TCP flow control with IOCP style async networking APIs here on my blog: [url="http://www.serverframework.com/asynchronousevents/2011/06/tcp-flow-control-and-asynchronous-writes.html"]http://www.serverframework.com/asynchronousevents/2011/06/tcp-flow-control-and-asynchronous-writes.html[/url]
2

Share this post


Link to post
Share on other sites
[quote name='Len Holgate' timestamp='1337358569' post='4941211']
I talk about the issues that you can come up against if you ignore TCP flow control with IOCP style async networking APIs here on my blog: http://www.serverfra...ous-writes.html
[/quote]

Thanks again for all the useful info, it's appreciated.
1

Share this post


Link to post
Share on other sites
This is not a direct answer to your question, but as a suggestion you might want to consider looking at [url="http://www.boost.org/doc/libs/1_49_0/doc/html/boost_asio.html"]Boost.Asio[/url] (or non-Boost [url="http://think-async.com/"]Asio[/url]). It's an asynchronous IO library that basically uses the best available methods on all supported platforms (which includes Solaris). On Windows, it uses IOCP. It includes a high-performance implementation of the highly scalable Proactor framework (and on systems without native asynchronous IO it will emulate it via a Reactor on the backend), and will free you from having to worry about most of the details and gotchas when working with IOCP at a low level.
0

Share this post


Link to post
Share on other sites
[quote name='Kaelb' timestamp='1337647065' post='4942049']
One more thing that's very good about IOCP is that it can manage the number of threads running so you don't have to waste context switches and it tries to maximize the the workd made by the threads, instead of wasting processor time context switching between them.
[/quote]

Yes, that's one thing i find interesting about it and i actually like the way it works. It should scale very nicely with the number of CPUs (cores) on machines.

we did take a look at SOAP like Taby said but considering the nature of what we're doing, it is not really appropriate. Don't get me wrong, those tools are really neat. I'll take a look at non-boost asio.

I have work on a small prototype and encontered a weird problem with my I/O worker threads. The server thread basically waits on an event that is triggered when a connection is received, her's the code for the thread routine :

[CODE]
int AsyncServer::Run()
{
bool bRunning = true;
DWORD iRet = 0;
HANDLE Events[SE_COUNT] = {0};
if(mIocp.Create(miConcurency))
{
if(mIoWorker.Initialize(&mIocp))
{
Events[SE_ACCEPT_EVENT] = mhAcceptEvent;
Events[SE_SHUTDOWN_EVENT] = mhShutdownEvent;
// Reset the shutdown event.
ResetEvent(mhShutdownEvent);
if(CreateListeningSocket(BACKLOG_COUNT))
{
if(WSAEventSelect(mListener, mhAcceptEvent, FD_ACCEPT) != SOCKET_ERROR)
{
while(bRunning)
{
DWORD iWaitResult = WaitForMultipleObjects(SE_COUNT, Events, FALSE, INFINITE);
switch(iWaitResult)
{
case WAIT_OBJECT_0:
{
ResetEvent(mhAcceptEvent);
//TEST
struct sockaddr_in remote = {0};
int iAddrLen = sizeof(remote);
DESCRIPTOR Socket = WSAAccept(mListener,
reinterpret_cast<struct sockaddr *>(&remote),
&iAddrLen,
NULL,
NULL);
closesocket(Socket);
TRACE(L"\n--- Accepted connection ---\n");
//END TEST
}
break;
case (WAIT_OBJECT_0 + 1):
{
// Shutdown the server.
bRunning = false;
//TEST
TRACE(L"\n--- Server shutting down ---\n\n");
//END TEST
}
break;
}
}
}
}
// Server shutdown.
ShotdownSequence();
}
}
return 0;
}
[/CODE]

The mIoWorker.Initialize does this :

[CODE]
bool bRetVal = true;
IOWorker *pWorker = NULL;
unsigned int iThreadCount = pIocp->GetConcurrentThreadCount();

mpIocp = pIocp;


mWorkers.reserve(iThreadCount);

for(unsigned int i = 0; i < iThreadCount; ++i)
{
pWorker = new(std::nothrow) IOWorker(pIocp);
if(pWorker)
{
mWorkers.push_back(pWorker);
bRetVal = bRetVal && pWorker->Start();
}
}
return bRetVal;
[/CODE]

So, in order to stop the thread, the mhShutdownEvent event is signaled which breaks the loop and gets to the ShotdownSequence method. The method called to stop the server basically only signal the event then calls WaitForSingleObject on the thread handle.

The ShotdownSequence() method does the following :

[CODE]
void AsyncServer::ShotdownSequence()
{
// Shutdown the I/O thread pool.
mIoWorker.Shutdown();
// Close the iocp.
mIocp.Close();
mbIsRunning = false;
}
[/CODE]

and mIoWorker.Shutdown() post a completion packet for each thread and waits for each thread to terminate :

[CODE]
void IOWorkerPool::Shutdown()
{
IOWorker *pWorker = NULL;
std::vector<IOWorker *>::iterator it;

for(unsigned int i = 0; i < mWorkers.size(); ++i)
{
mpIocp->PostIoCompletionOperation(NULL);
}
for(unsigned int i = 0; i < mWorkers.size(); ++i)
{
mWorkers[i]->Wait();
}
while(mWorkers.size())
{
pWorker = (*mWorkers.begin());
delete pWorker;
mWorkers.erase(mWorkers.begin());
}
pWorker = NULL;
}
[/CODE]

The problem i have with this is that it freezes once in a while waiting on a thread (ramdom one) when it shutsdown. However, the threads all terminate normaly. If i put a Sleep(2000) as a test instead of the loop that calls mWorkers[i]->Wait(), everything terminate just fine (Sleep is just for a test). The wait method simply calls WaitForSingleObject on the thread handle. I really don't see what happens ....

The I/O workers only do the following so far :

[CODE]
int IOWorker::Run()
{
DWORD iBytes = 0;
ConnectionLink *pLink = NULL;
LPOVERLAPPED pOverlapped = NULL;

while(mbIsRunning)
{
if(mpIocp->GetIoCompletionOperation(&iBytes, &pLink, &pOverlapped))
{
if(pLink)
{
}
else
{
mbIsRunning = false;
}
}
}
return 0;
}
[/CODE]

Edit :

Is it wrong to use WaitForSingleObject to wait for a thread to terminate (or at least to call it many times in row) ? Edited by Laval B
2

Share this post


Link to post
Share on other sites
Ok, i found what the problem is and i thought i might as well mention it since it is related to the Win32 thread api. Alot of you probably know that already.

The problem was hiding in my thread class. I was using _beginthread to create the thread. Reading the [url="http://msdn.microsoft.com/en-us/library/kdzttdcb(v=vs.80).aspx"]Microsoft documentation[/url] i learnt that this function may not always return a valid handle (especially if the thread terminates too quickly) which can cause WaitForSingleObject to hang. One solution is to call endthread/endthreadex explicitly at the end of the thread function. A better solution is simply to use _beginthreadex which solved the problem. It also uses a thread function that returns a value which will be the return code of the thread (that can be forced with endthreadex).


Edit :

I would also like to add, @[url="http://www.gamedev.net/user/147070-krippy2k8/"]krippy2k8[/url], the non-boost asio looks like a very nice library. Edited by Laval B
2

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0