21.03.2013 Views

Problem - Kevin Tafuro

Problem - Kevin Tafuro

Problem - Kevin Tafuro

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

#define SPC_ACQUIRE_MUTEX(mtx) pthread_mutex_lock(&(mtx))<br />

#define SPC_RELEASE_MUTEX(mtx) pthread_mutex_unlock(&(mtx))<br />

#define SPC_CREATE_COND(cond) (!pthread_cond_init(&(cond), 0))<br />

#define SPC_DESTROY_COND(cond) pthread_cond_destroy(&(cond))<br />

#define SPC_SIGNAL_COND(cond) pthread_cond_signal(&(cond))<br />

#define SPC_BROADCAST_COND(cond) pthread_cond_broadcast(&(cond))<br />

#define SPC_WAIT_COND(cond, mtx) pthread_cond_wait(&(cond), &(mtx))<br />

#define SPC_CLEANUP_PUSH(func, arg) pthread_cleanup_push(func, arg)<br />

#define SPC_CLEANUP_POP(exec) pthread_cleanup_pop(exec)<br />

#define closesocket(sock) close((sock))<br />

#define SOCKET_ERROR -1<br />

#else<br />

#define SPC_ACQUIRE_MUTEX(mtx) WaitForSingleObjectEx((mtx), INFINITE, FALSE)<br />

#define SPC_RELEASE_MUTEX(mtx) ReleaseMutex((mtx))<br />

#define SPC_CREATE_COND(cond) ((cond) = CreateEvent(0, TRUE, FALSE, 0))<br />

#define SPC_DESTROY_COND(cond) CloseHandle((cond))<br />

#define SPC_SIGNAL_COND(cond) SetEvent((cond))<br />

#define SPC_BROADCAST_COND(cond) PulseEvent((cond))<br />

#define SPC_WAIT_COND(cond, mtx) spc_win32_wait_cond((cond), (mtx))<br />

#define SPC_CLEANUP_PUSH(func, arg) { void (*__spc_func)(void *) = func; \<br />

void *__spc_arg = arg;<br />

#define SPC_CLEANUP_POP(exec) if ((exec)) __spc_func(__spc_arg); } \<br />

do { } while (0)<br />

#endif<br />

static int socketpool_used = 0;<br />

static int socketpool_limit = 0;<br />

#ifndef WIN32<br />

static pthread_cond_t socketpool_cond = PTHREAD_COND_INITIALIZER;<br />

static pthread_mutex_t socketpool_mutex = PTHREAD_MUTEX_INITIALIZER;<br />

#else<br />

static HANDLE socketpool_cond, socketpool_mutex;<br />

#endif<br />

#ifdef WIN32<br />

static void spc_win32_wait_cond(HANDLE cond, HANDLE mutex) {<br />

HANDLE handles[2];<br />

handles[0] = cond;<br />

handles[1] = mutex;<br />

ResetEvent(cond);<br />

ReleaseMutex(mutex);<br />

WaitForMultipleObjectsEx(2, handles, TRUE, INFINITE, FALSE);<br />

}<br />

#endif<br />

int spc_socketpool_init(void) {<br />

#ifdef WIN32<br />

if (!SPC_CREATE_COND(socketpool_cond)) return 0;<br />

if (!(socketpool_mutex = CreateMutex(0, FALSE, 0))) {<br />

CloseHandle(socketpool_cond);<br />

return 0;<br />

}<br />

Guarding Against Creating Too Many Network Sockets | 725<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!