I read code about socket used in multithread, the code is as follows:
function main
int main(void)
{
int listenfd;
int i = 0;
/* check envirenment */
if (check_env() == FALSE)
{
return 0;
}
/* get the bind port */
listenfd = initserver(PORT);
if ( listenfd == -1 )
{
return 0;
}
/* initial the message queue. */
/* and start to run ...*/
initDatas(listenfd);
/* start already.........*/
/* make the main thread be a thread which recive the requst from
* client */
fMsgIn((void *)&listenfd);
return 0;
}
function initDatas
void initDatas(socketfd fd)
{
int num_accept_req = 5;
int num_go = 5;
int num_getblg = 5;
/* control userbuf */
init_userbuf();
/* init the ctrlsockfd list */
init_ctrlsockfd();
/* run server */
init_accept_req(fd, num_accept_req);
/* get blog */
init_getblg(num_getblg);
/* put blog */
// init_pubblg(num_pubblg);
/* get personal msg */
// init_getprsnalmsg(num_getprsnalmsg);
/* pub personal msg */
// init_pubprsnalmsg(num_pubprsnalmsg);
/*get followers */
// init_getfollower(num_getfollower);
/* set personal information */
//init_setprsnalinfo(num_setprsnalinfo);
/* send out dates ...*/
init_msgout(num_go);
}
function init_accept_req
void init_accept_req(socketfd fd, int number_thread)
{
#ifdef DEBUG
printf("\ninitial thread for accept request !\n");
ASSERT(number_thread >= 1 && fd > 0);
#endif
pthread_t *pid;
pthread_attr_t attr;
int i = 0;
pid = Malloc_r(number_thread * sizeof(pthread_t));
if ( pid == NULL )
err_quit("malloc, in init_accept_req");
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
for ( i = 0; i < number_thread; i++ )
{
/* control accept requst */
pthread_create(pid + i, &attr, (void *)fMsgIn, (void*)&fd);
}
}
we can see that socket file descriptor listenfd
is created by function initserver
, and in function init_accept_req
, multithread is created and linux socket function accept
is called in the callback function of these thread, namely function fMsgIn
, so my question is when multithreads are using the same socket fd, aren't there any conficts between these threads?(note that there are no synchronization primitives in these threads when call linux socket function accept
)?