Locking Message Buffers to use them with multiple writers

Hello there,

according to the source:

if there are multiple writers,e.g. multiple tasks, I have to wrap the writing API calls with a “critial section”. This sounds like a very strict rule and thus I came up with this code:

		taskENTER_CRITICAL();
		bytes_sent = xMessageBufferSend(	message_buffer_handle,
												pSendBuffer,
												NumBytes,	/* chars - we don't know anything about final null byte */
												0  /*! leave at 0 because we are in a critical section */
												);
		taskEXIT_CRITICAL();

However, the documentation states that a critical section is only one way to serialize calls to writing API functions, see here:

Source and documentation seem a little bit divergent (or rather contradictory).

What would be a more lightweight way to achieve proper serialization for multiple writers? Would a FreeRTOS Mutexes be sufficient?

Thank you.
Daniel

PS: edited to add the links

You don’t actually need a critical section, I have used a Mutex to protect the shared end. The one thing to remember is that this doesn’t fully respect the priority of the requestors, as first to the mutex gets it, and only if multiple tasks are waiting to get it will priority matter.

(You could make the blocking be just for 1 tick at a time, and if not granted, release the mutex then reacquire and wait for another tick which limits the delay of the higher priority task at the cost of a bit more CPU during the waiting).

The key requirement is that one source/destination can’t try to use the Buffer while another task is blocked on it, as part of the improvements for the Buffers is removing that arbitration code, so you can use the mutex to get it back.

1 Like

The documentation on the website is the correct one. We will update the comments. Thank you for pointing it.

@richard-damon has already suggested a solution and the potential pitfalls.

You should now be able to post links.

1 Like

This PR addresses it - Update stream and message buffer documentation by aggarg · Pull Request #1226 · FreeRTOS/FreeRTOS-Kernel · GitHub.

1 Like