diff --git a/src/AsyncTCP.cpp b/src/AsyncTCP.cpp index 5259400..9071ead 100644 --- a/src/AsyncTCP.cpp +++ b/src/AsyncTCP.cpp @@ -78,9 +78,20 @@ typedef struct { static xQueueHandle _async_queue; static TaskHandle_t _async_service_task_handle = NULL; + + +SemaphoreHandle_t _slots_lock; const int _number_of_closed_slots = CONFIG_LWIP_MAX_ACTIVE_TCP; -static int _closed_index = 0; static int _closed_slots[_number_of_closed_slots]; +static int _closed_index = []() { + _slots_lock = xSemaphoreCreateBinary(); + xSemaphoreGive(_slots_lock); + for (int i = 0; i < _number_of_closed_slots; ++ i) { + _closed_slots[i] = 1; + } + return 1; +}(); + static inline bool _init_async_event_queue(){ if(!_async_queue){ @@ -554,22 +565,16 @@ AsyncClient::AsyncClient(tcp_pcb* pcb) _pcb = pcb; _closed_slot = -1; if(_pcb){ - _closed_slot = 0; - if (_closed_index == 0) { - _closed_index = 1; - for (int i = 0; i < _number_of_closed_slots; ++ i) { - _closed_slots[i] = 1; - } - } else { - int closed_slot_min_index = _closed_slots[0]; - for (int i = 0; i < _number_of_closed_slots; ++ i) { - if (_closed_slots[i] <= closed_slot_min_index && _closed_slots[i] != 0) { - closed_slot_min_index = _closed_slots[i]; - _closed_slot = i; - } + xSemaphoreTake(_slots_lock, portMAX_DELAY); + int closed_slot_min_index = 0; + for (int i = 0; i < _number_of_closed_slots; ++ i) { + if ((_closed_slot == -1 || _closed_slots[i] <= closed_slot_min_index) && _closed_slots[i] != 0) { + closed_slot_min_index = _closed_slots[i]; + _closed_slot = i; } } _closed_slots[_closed_slot] = 0; + xSemaphoreGive(_slots_lock); _rx_last_packet = millis(); tcp_arg(_pcb, this);