对于每个客户端连接,我将在单独的std::thread
中处理到套接字的传入连接。因此,当尝试从套接字执行read()
时,程序会崩溃。
std::thread in_conn_th(handle_new_connection, in_socket); // <-- creating a new thread and passing the handle_new_connection function into the thread with the socket descriptor param
以下是handle_new_connection()
的说明
waiterr::operation_codes waiterr::Waiter::handle_new_connection(int incoming_socket) {
std::cout << "Here comes " << incoming_socket << "n";
char buffer[30000] = {0};
int val_read = read(incoming_socket, buffer, 30000); // <-- Error
std::cout << "Here comes 2n";
std::cout << buffer << std::endl << std::endl;
write(incoming_socket, "Some response", 13);
std::cout << "* Msg sent *n";
close(incoming_socket);
return operation_codes(OK);
}
错误
shantanu@Shantanus-MacBook-Pro webserver % ./test1.o
* Waiting for new connection *
libc++abi: terminating
Here comes 4
zsh: abort ./test1.o
如果我只是在没有生成新线程的情况下调用handle_new_connection()
,那么操作是成功的,并且在客户端中显示响应。
所以我很确定这是关于一些我不知道的线索。
环境-苹果M1硅;在ARM上本机运行g++。
编辑handle_new_connection()
的函数定义
static enum operation_codes handle_new_connection(int incoming_socket);
我用了pthread_t
而不是std::thread
,效果很好。
代替
std::thread in_conn_th(handle_new_connection, in_socket);
我使用
pthread_t in_conn_th;
pthread_create(&in_conn_th, NULL, handle_new_connection, (void*)(&in_socket));
并更改了接收void *
的功能定义
不要忘记包含pthread.h
标头。