From 0c4748cdeb4b9f4c36f4222ccc1652d4d486cb0c Mon Sep 17 00:00:00 2001 From: wangzhengquan <wangzhengquan85@126.com> Date: 星期三, 02 十二月 2020 11:07:31 +0800 Subject: [PATCH] uddate --- src/socket/shm_socket.c | 61 ++++++++++++++++++++++++++++-- 1 files changed, 56 insertions(+), 5 deletions(-) diff --git a/src/socket/shm_socket.c b/src/socket/shm_socket.c index 8fc4d94..fe25e3c 100644 --- a/src/socket/shm_socket.c +++ b/src/socket/shm_socket.c @@ -374,25 +374,76 @@ } } +static pthread_once_t _once_ = PTHREAD_ONCE_INIT; +static pthread_key_t _tmp_recv_socket_key_; + + /* Free thread-specific data buffer */ +static void _destrory_tmp_recv_socket_(void *tmp_socket) +{ + logger->debug("%d destroy tmp socket\n", pthread_self()); + shm_close_socket((shm_socket_t *)tmp_socket); +} + +/* One-time key creation function */ +static void _create_tmp_recv_socket_key(void) +{ + int s; + + /* Allocate a unique thread-specific data key and save the address + of the destructor for thread-specific data buffers */ + s = pthread_key_create(&_tmp_recv_socket_key_, _destrory_tmp_recv_socket_); + if (s != 0) { + logger->error(s, "pthread_key_create"); + abort(); /* dump core and terminate */ + exit(1); + } +} + + + int shm_sendandrecv(shm_socket_t *socket, const void *send_buf, const int send_size, const int send_key, void **recv_buf, int *recv_size, struct timespec *timeout, int flags) { + int recv_key; + int rv; + + // 鐢╰hread local 淇濊瘉姣忎釜绾跨▼鐢ㄤ竴涓嫭鍗犵殑socket鎺ュ彈瀵规柟杩斿洖鐨勪俊鎭� + shm_socket_t *tmp_socket; + if (socket->socket_type != SHM_SOCKET_DGRAM) { logger->error( "shm_socket.shm_sendandrecv: Can't invoke shm_sendandrecv method in a %d type socket " "which is not a SHM_SOCKET_DGRAM socket ", socket->socket_type); exit(1); } - int recv_key; - int rv; + - shm_socket_t *tmp_socket = shm_open_socket(SHM_SOCKET_DGRAM); + rv = pthread_once(&_once_, _create_tmp_recv_socket_key); + if (rv != 0) { + logger->error(rv, "shm_sendandrecv pthread_once"); + exit(1); + } + + tmp_socket = (shm_socket_t *)pthread_getspecific(_tmp_recv_socket_key_); + if (tmp_socket == NULL) + { + /* If first call from this thread, allocate buffer for thread, and save its location */ + logger->debug("%d create tmp socket\n", pthread_self() ); + tmp_socket = shm_open_socket(SHM_SOCKET_DGRAM); + + rv = pthread_setspecific(_tmp_recv_socket_key_, tmp_socket); + if (rv != 0) { + logger->error(rv, "shm_sendandrecv : pthread_setspecific"); + exit(1); + } + } + if ((rv = shm_sendto(tmp_socket, send_buf, send_size, send_key, timeout, flags)) == 0) { rv = shm_recvfrom(tmp_socket, recv_buf, recv_size, &recv_key, timeout, flags); - shm_close_socket(tmp_socket); + return rv; } else { - shm_close_socket(tmp_socket); + return rv; } return -1; -- Gitblit v1.8.0