Managing Global varibles used by multiple threads

Hello,

I am new to rtos and have some difficulty in understanding how to manage global variables or shared resource in rtos environment so please look into below example and guide.

i have one global array variable which is going to be updated by thread_1. thread_2 and thread_3 only reads data without modifying this array variable.
In this case should i use mutex or any other synchronization method to guard array variable or i can read this array variable without any protection just like we do in non rtos programming.

please check below two approaches and guide which is good to go with.

float arr[100];

Approach 1 :

    void thread_1
    {
    	while(1)
    	{
    		// update data  in arr[] variable
    	}
    }

void thread_2
{
	while(1)
	{
		// only read data from arr[] variable
	}
}

void thread_3
{
	while(1)
	{
		// only read data from arr[] variable
	}
}


Approach 2 :

Mutex my_mutex;

void thread_1
{
	while(1)
	{
	    my_mutex.lock();
	    // update data  in arr[] variable
	    my_mutex.unlock();		
	}
}

void thread_2
{
	while(1)
	{
	    my_mutex.lock();
	    // only read data from arr[] variable
	    my_mutex.unlock();	
	}
}

void thread_3
{
	while(1)
	{
	    my_mutex.lock();
	    // only read data from arr[] variable
	    my_mutex.unlock();	
	}
}

Hi,

The main rule in multi-threaded code is to not make any assumptions about how the threads will execute on your single processor. In fact, it is best to assume that the interleaving of the thread executions will be nasty and horrible. With this in mind, you must protect all accesses to global variables. If you think debugging single threaded code is difficult, debugging muti-threaded code is much more difficult because it can lead to obscure time related problems that can be near impossible to replicate and diagnose (been there and have the T-shirt! ).

Approaches

  1. Design to keep the number of global variables to a minimum. The extra protection code can eat into your compute time budget.

  2. The simplest protection is to use MUTEXES/SEMAPHORES. All RTOSs will provide these.

  3. Packaged structures (e.g. queues, pipes, etc) hide the messy detail of the protection mechanism. I’m using MBED queues on my current project, and they seem to work pretty well.

  4. Minimise the area of code that needs protection, ie. to the code that actually accesses the global variable. If you expand the protected area too much, then you may block other more important threads.

Best of luck.

Jim

1 Like

when you say update, what do you mean? rewrite the entire array? append at the end?
same with read, do you read the entire array? juste the beginning? the end?

queues, circular buffers and so on can be really useful.

I personally like to encapsulate such constructs into a new class so I can change the underlying storage structure without changing the code everywhere.