gpt4 book ai didi

c - 线程函数内的奇怪行为

转载 作者:行者123 更新时间:2023-11-30 17:04:16 25 4
gpt4 key购买 nike

我有一个用 C 语言编写的服务器程序,带有线程函数 join_handler。当我在 main 中调用此函数时,语句后什么都没有 - printf("inside join handler %d",newsock); 在线程函数内部执行。

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<string.h>
#include<stdlib.h>
#include<arpa/inet.h>
#include<pthread.h>
#define SERVER_PORT 5498
#define MAX_LINE 256
#define MAX_PENDING 5
#define MAXNAME 256
int req_no;
char packet_type[50];
//void* join_handler(struct*);
struct packet{
short type;
char data[MAXNAME];
};
struct packet packet_reg;

struct global_table{
int sockid;
int reqno;
};
struct global_table record[20];

void *join_handler(void *rec)
{
//pthread_mutex_t my_mutex= PTHREAD_MUTEX_INITIALIZER;
int *newsock;
newsock=(int*)rec;
printf("inside join handler %d",newsock); /// the last statement which gets executed
printf("\n %d",newsock);

if(recv(newsock,&packet_reg,sizeof(packet_reg),0)<0)
{
printf("\n Could not receive \n");
exit(1);
}
printf("\n joinhandler sockid is %d",newsock);
//other operation

pthread_exit(NULL);
}



int main(int argc, char* argv[])
{

pthread_t threads[2];
struct sockaddr_in sin;
struct sockaddr_in clientAddr;
char buf[MAX_LINE];
int s, new_s;
struct in_addr addr;
struct hostent *host;
int len;
struct registrationTable
{
int port;
char name[MAXNAME];
int req_no;
};
struct registrationTable table[10];

int *exit_value;
req_no=0;
char clientname[500];

/* setup passive open */
if((s = socket(PF_INET, SOCK_STREAM, 0)) < 0){
perror("tcpserver: socket");
exit(1);
}


/* build address data structure */
bzero((char*)&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(SERVER_PORT);


if(bind(s,(struct sockaddr *)&sin, sizeof(sin)) < 0){
perror("tcpclient: bind");
exit(1);
}
listen(s, MAX_PENDING);

/* wait for connection, then receive and print text */
while(1){
if((new_s = accept(s, (struct sockaddr *)&clientAddr, &len)) < 0){
perror("tcpserver: accept");
exit(1);
}


recv(new_s,&packet_reg, sizeof(packet_reg), 0);
if(recv(new_s,&packet_reg, sizeof(packet_reg), 0)<0)
{
printf("\n Could not receive first registration packet \n");
exit(1);
}

pthread_create(&threads[0],NULL,join_handler,new_s);
pthread_join(threads[0],&exit_value);

}
}

最佳答案

在\n 之前您不会看到任何输出。因此,您不会看到此行被执行:

printf("\n %d",newsock);

这并不意味着它没有执行,只是输出被缓冲了,并且在recv接收到一些东西之前你不会看到它。但是,我的猜测是,直到您将某些内容发送回客户端之前,它不会发生,因为您在启动线程之前读取了第一个数据包。

关于c - 线程函数内的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35881303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com