| | |
| | | } |
| | | } |
| | | |
| | | 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; |
| | | |
| | | // 用thread 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; |