multithreading - posix multithread.With Multiple threas using one socket to receive data , when will the data be taken away from recv buffer? -
i use multuple thread receive data 1 socket. can receive same data. want know when data taken away recv buffer? why not 1 thread receive next data when former thread read former data.
pthread_create(&(ntid[i]), null, find_host, (void *)&start_addr); int find_host(void * arg) { int sockfd; unsigned long ip ; tv.tv_sec = 0; tv.tv_usec = 100000; struct sockaddr_in from; char sendpacket[packet_size]; char recvpacket[packet_size]; ip = *(unsigned long *)arg; struct sockaddr_in present_addr; if( (sockfd=socket(af_inet,sock_raw,protocol->p_proto) )<0) { perror("socket error"); exit(1); } setsockopt(sockfd,sol_socket,so_rcvbuf,&size,sizeof(size) ); if(setsockopt(sockfd, sol_socket, so_rcvtimeo, &tv, sizeof(tv))<0){ printf("socket option so_rcvtimeo not support\n"); return; } bzero(&present_addr,sizeof(present_addr)); present_addr.sin_family=af_inet; present_addr.sin_addr.s_addr = htonl(ip); pthread_mutex_unlock(&lock); printf("ping (%s): %d bytes data in icmp packets.\n", inet_ntoa(present_addr.sin_addr),icmp_data_len); send_packet(sockfd, sendpacket, present_addr); recv_packet(sockfd, recvpacket, from); close(sockfd); } void recv_packet(int sockfd, char * recvpacket, struct sockaddr_in from) { int n,from_len; extern int errno; int nreceived = 0; struct timeval recv_time; from_len = sizeof(from); while (nreceived < max_send_times) { if((n=recvfrom(sockfd,recvpacket, packet_size, 0, (struct sockaddr *)&from,&from_len)) <0) { if(errno == ewouldblock || errno== eagain ) { printf("recvfrom timeout!!!!\n"); pthread_exit(null); } } gettimeofday(&recv_time,null); if (1 == unpack(recv_time, recvpacket, n, from)) { printf(" find %u\n", (unsigned short)pthread_self()); nreceived++; } else printf(" not find\n"); } }
Comments
Post a Comment