- 论坛徽章:
- 1
|
tcp服务器程序:- int main()
- {
- .........
- .........
- int listenfd,connectfd;
- char buff[1024];
- pthread_t ptid;
- listenfd=listen(..);
- while(1)
- {
- connectfd=accept( listenfd , struct sockaddr*addr...);
- recv(...,buf,...)
- pthread(&ptid,NULL,fun,(void *) buf);
- }
- return 0;
- }
- void fun(void * buf)
- {
-
- printf("%d",(char *) buf);//问题1:线程1进入fun但printf还没调用前,cpu切换到线程2,也就是在第二次accept和receive后,cpu又切换到线程1,但此时buff里面是线程2的数据,如何避免
-
- //函数结束时要不要关闭connectfd,close(connectfd)
- }
复制代码 udp服务器程序:
int main()
{
......
int fd,ptid;
char buff[512];
struct sockaddr_in clientAddr;//用来存储客户端传来的信息
int n;
int len = sizeof(clientAddr);
while(1)
{
n = recvfrom(sock, buff, sizeof(buff), 0, (struct sockaddr*)&clientAddr, &len);
if (n>0)
{
pthread_t ptid;
pthread_create(&ptid,NULL,fun,(void*) clientAddr);
}
return 0;
}
void fun(void *arg)
{
printf("%d",(struct sockaddr_in) arg.sin_addr.s_addr);//问题同 问题1
//函数结束时要不要关闭connectfd,close(connectfd)
} |
|