From ea8729acc499782ced26e7ba16f6d35e3abc1d82 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 18 Jan 2013 11:18:54 -0800 Subject: [PATCH] better concurrency management for shared buffer --- socket.cpp | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/socket.cpp b/socket.cpp index d057a1a750..b41681b8b3 100644 --- a/socket.cpp +++ b/socket.cpp @@ -22,6 +22,8 @@ const int LOGOFF_CHECK_INTERVAL = 1000; const float BUFFER_SEND_INTERVAL = (SAMPLES_PER_PACKET/SAMPLE_RATE) * 1000; +pthread_mutex_t buffer_mutex = PTHREAD_MUTEX_INITIALIZER; + int16_t* packet_buffer; sockaddr_in address, dest_address; @@ -134,12 +136,19 @@ void *send_buffer_thread(void *args) // send out whatever we have in the buffer as mixed audio // to our recent clients + for (int i = 0; i < num_agents; i++) { if (agents[i].active) { sockaddr_in dest_address = agents[i].agent_addr; - sent_bytes = sendto(handle, packet_buffer, MAX_PACKET_SIZE, - 0, (sockaddr *) &dest_address, sizeof(sockaddr_in)); + pthread_mutex_lock(&buffer_mutex); + + if (packet_buffer != NULL) { + sent_bytes = sendto(handle, packet_buffer, MAX_PACKET_SIZE, + 0, (sockaddr *) &dest_address, sizeof(dest_address)); + } + + pthread_mutex_unlock(&buffer_mutex); if (sent_bytes < MAX_PACKET_SIZE) { std::cout << "Error sending mix packet! " << sent_bytes << strerror(errno) << "\n"; @@ -165,6 +174,8 @@ void *process_client_packet(void *args) sockaddr_in dest_address = process_args->dest_address; + pthread_mutex_lock(&buffer_mutex); + if (packet_buffer == NULL) { packet_buffer = process_args->packet_data; } else { @@ -173,6 +184,8 @@ void *process_client_packet(void *args) } } + pthread_mutex_unlock(&buffer_mutex); + if (addAgent(dest_address)) { std::cout << "Added agent: " << inet_ntoa(dest_address.sin_addr) << " on " <<