当前位置: 技术问答>linux和unix
Linux下 socket多线程问题
来源: 互联网 发布时间:2016-07-10
本文导语: 本人刚开始编Linux下sock和多线程有一些问题 我在服务器循环中,接收客户端请求,我不用多线程时候可以正确读出数据 while (1) { m_connfd = accept(m_listenfd, (struct sockaddr*) NULL, NULL); clientSession *new_session = ...
本人刚开始编Linux下sock和多线程有一些问题
我在服务器循环中,接收客户端请求,我不用多线程时候可以正确读出数据
while (1)
{
m_connfd = accept(m_listenfd, (struct sockaddr*) NULL, NULL);
clientSession *new_session = new clientSession(m_connfd);
new_session->ReadData();
}
但是我使用多线程处理客户端数据后发现读出数据不正确,请大家帮我看看
while (1)
{
m_connfd = accept(m_listenfd, (struct sockaddr*) NULL, NULL);
pthread_attr_t attr;
pthread_t id;
int ret;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); //设置为分离线程
pthread_t id;
pthread_create(&id, NULL ,thread, (void*)&m_connfd);
}
线程函数
void *thread(void *arg)
{
clientSession client(*(int *)arg);
client.ReadData();
}
我在服务器循环中,接收客户端请求,我不用多线程时候可以正确读出数据
while (1)
{
m_connfd = accept(m_listenfd, (struct sockaddr*) NULL, NULL);
clientSession *new_session = new clientSession(m_connfd);
new_session->ReadData();
}
但是我使用多线程处理客户端数据后发现读出数据不正确,请大家帮我看看
while (1)
{
m_connfd = accept(m_listenfd, (struct sockaddr*) NULL, NULL);
pthread_attr_t attr;
pthread_t id;
int ret;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); //设置为分离线程
pthread_t id;
pthread_create(&id, NULL ,thread, (void*)&m_connfd);
}
线程函数
void *thread(void *arg)
{
clientSession client(*(int *)arg);
client.ReadData();
}
|
看上去没啥问题,不知道你的clientSession是怎么实现的.