Page 1 of 1

Mutex, Semaphore, neither, other?

Posted: Fri May 04, 2018 11:08 pm
by rbarreiros
Hi,

I made a small network stack that's just meant to do ARP/ICMP and UDP, so its really small and fast (faster than uIP) and I have 1 thread handling the network traffic that calls callbacks based on which port the higher level api has registered. The network buffer is shared for data received and sent (like uIP) to save memory. So thread is something like this in pseudo code:

Code: Select all

While(1)
{
  Wait interrupt with data ready to read
  If read size > 0
    Process packet
  Endif
}


Now, while the packet is being processed, the buffer contents can be changed and used as the reply data if there is a reply, so far so good, but, sometimes, I have to send a sporadic packet outside of that thread packet processing, I have to figure out a way of just sending those packets when there is no packet being processes.

How would you guys tackle this issue ?

Best regards.

Re: Mutex, Semaphore, neither, other?

Posted: Sat May 05, 2018 6:46 am
by Giovanni
It is not very clear to me, do you have a single buffer?

Giovanni

Re: Mutex, Semaphore, neither, other?

Posted: Sat May 05, 2018 9:50 am
by rbarreiros
Exactly, that can't be changed by anything outside the network thread as soon as its started to be processed.

But sometimes I have to use the same buffer to send sporadic packets outside the thread processing loop.

Mutex on the buffer?

Re: Mutex, Semaphore, neither, other?

Posted: Sat May 05, 2018 9:58 am
by Giovanni
Yes, mutex on buffer, assuming that the buffer is contended only by threads, not ISRs nor callbacks.

Giovanni

Re: Mutex, Semaphore, neither, other?

Posted: Sat May 05, 2018 6:51 pm
by rbarreiros
But he is used in callbacks. The application registers a callback tied to a port, then, in the thread, if the packet matches the registered destination port, calls the callback to process the data (same buffer, pointer at the data index), is it still safe to use the mutex like this?

Re: Mutex, Semaphore, neither, other?

Posted: Sat May 05, 2018 7:02 pm
by Giovanni
You cannot use mutex from callbacks of course.

The only way to share something between an ISR and a thread is a critical zone, chSysLock()/chSysUnlock() but that is not always possible if you need to perform long operations,

An alternative would be your ISR delegating the access to a dedicated thread, then the mutex would be usable.

Giovanni