我对套接字和线程都不熟悉。我有这段代码:
listen(socket_fd, 20);
/* Looooop */
while (1) {
newsocket_fd = accept(socket_fd,
(struct sockaddr *) &client_addr,
&client_len);
if (newsocket_fd < 0) {
error("ERROR on accept");
}
pthread_t thread;
pthread_create(&thread, NULL, run_thread, (void *) newsocket_fd);
pthread_join(thread, NULL);
}
如何为每个新连接而不是为每个请求启动一个新线程?这些线程应该在新连接进来时启动,然后这些线程应该等待请求、处理这些请求,最后在连接关闭时返回。 每个连接应该有一个线程。下面是run_thread
的代码:
void
*run_thread(void *ptr) {
char buffer[256];
bzero(buffer, 256);
int n;
n = read((int) ptr, buffer, 255);
if (n < 0) error("ERROR Reading from socket");
printf("%s\n\n**********\n\n", buffer);
/* Parse buffer and return result */
char *result;
{
/* First, determine command, 4 characters */
/* (much code) */
}
n = write((int) ptr, result, strlen(result));
if (n < 0) error("ERROR Writing to socket");
}
谁能帮帮我?谢谢。
最佳答案
还有一个不同的严重错误。
您将 int 转换为 (void*)。这根本不符合逻辑。此外,您不能直接传递地址,因为在线程可以将变量复制到其本地堆栈之前,变量可能会在下一次 accept() 调用时更改。一种写法是这样的:
while (1) {
newsocket_fd = accept(socket_fd,
(struct sockaddr *) &client_addr,
&client_len);
if (newsocket_fd < 0) {
error("ERROR on accept");
}
pthread_t thread;
int *newsock = malloc(sizeof(int));
*newsock = newsocket_fd;
pthread_create(&thread, NULL, run_thread, newsock);
pthread_detach(thread);
}
使用这种方法,线程将确保 free() newsock。例如一个简单的
void *handler(void *thread_data) {
int fd = *(int *) thread_data;
free(thread_data);
....
}
此外,如果主程序不关心稍后使用 pthread_join() 与线程同步,我假设 pthread_detach() 没问题。
关于c - 使用 C 的套接字和线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3719462/