|
Multithreading a server
All the arguments must be collected into a struct, since only one argument
pointer can be sent to the pthread functions.
#include
<pthread.h>
SpawnCfGetFile(args)
struct cfd_thread_arg
*args;
{ pthread_t tid;
void *CfGetFile();
pthread_attr_init(&PTHREADDEFAULTS);
pthread_attr_setdetachstate(&PTHREADDEFAULTS,PTHREAD_CREATE_DETACHED);
if
(pthread_create(&tid,&PTHREADDEFAULTS,CfGetFile,args) !=
0)
{
CfLog(cferror,"pthread_create
failed","create");
CfGetFile(args);
}
pthread_attr_destroy(&PTHREADDEFAULTS);
}
/***************************************************************/
void *CfGetFile(args)
struct cfd_thread_arg
*args;
{ pthread_mutex_t mutex;
if (pthread_mutex_lock(&mutex) !=
0)
{
CfLog(cferror,"pthread_mutex_lock
failed","pthread_mutex_lock");
free(args->replyfile); /* from strdup
in each thread */
DeleteConn(args->connect);
free((char *)args);
return NULL;
}
ACTIVE_THREADS++; /* Global variable
*/
if (pthread_mutex_unlock(&mutex) !=
0)
{
CfLog(cferror,"pthread_mutex_unlock
failed","unlock");
}
/* send data */
if (pthread_mutex_lock(&mutex) !=
0)
{
CfLog(cferror,"pthread_mutex_lock
failed","pthread_mutex_lock");
return;
}
ACTIVE_THREADS--;
if (pthread_mutex_unlock(&mutex) !=
0)
{
CfLog(cferror,"pthread_mutex_unlock
failed","unlock");
}
#endif
return NULL;
}
|