Question

I am having 2 threads Thread1 and Thread2. And I do have a function for a peripheral read or write. Say a SPI read or Write function. Both the threads are using SPI functions at some instances. Since the threads are concurrent in nature, is there any possibility for both the threads try to access the function at the same time. That is the Thread1 one wants to write 0x10 0x25 to the SPI. And The Thread2 wants to write 0x20 0x56. If any synchronization mechanism is not used, is there a possibility of writing wrong sequence to the SPI buffer ?

Was it helpful?

Solution

Consider your SPI a shared resource (critical section), which must be mutually exclusive.

Here is the general scheme for preventing a context-switch during SPI-access operations:

static pthread_mutex_t _mutex;

void SPI_init()
{
    ...
    pthread_mutex_init(&_mutex);
    ...
}

void SPI_read(...)
{
    pthread_mutex_lock(&_mutex);
    ...
    pthread_mutex_unlock(&_mutex);
}


void SPI_write(...)
{
    pthread_mutex_lock(&_mutex);
    ...
    pthread_mutex_unlock(&_mutex);
}

OTHER TIPS

Threads can be scheduled in any order. So, yes you can write wrong sequence to the peripheral registers.

And so, to avoid that use synchronization primitives!

See this basic tutorial on how to use mutex: http://www.thegeekstuff.com/2012/05/c-mutex-examples/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top