【发布时间】:2014-03-14 23:29:42
【问题描述】:
我看了多线程中使用socket的代码,代码如下:
主函数
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;
}
函数初始化数据
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);
}
函数 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);
}
}
我们可以看到socket文件描述符listenfd是由函数initserver创建的,在函数init_accept_req中创建了多线程,在这些线程的回调函数中调用了linux socket函数accept,即function fMsgIn,所以我的问题是,当多线程使用相同的套接字 fd 时,这些线程之间没有任何冲突吗?(请注意,当调用 linux 套接字函数 accept 时,这些线程中没有同步原语)?
【问题讨论】:
-
这些代码 sn-ps 不包含您询问的关键功能。但是相信这些功能会按照您的描述进行,这是安全的。只有一个线程可以接受同一个连接,并且每个线程都是一个单独的套接字。
-
Is accept() thread-safe? 的可能重复项
-
OT:为什么和什么是
socketfd?
标签: c linux multithreading sockets