[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Shared memory synchronization




I have some problems synchronizing shared mem access.

My RT-thread uses shared memory (mbuff) to get some info what to do. I
would like to be changing this shared memory from user space. Thus to
ensure the atomic changes of the shm data, I created two identical
structures in shm and a variable to point to the valid part of the data.
>From user space I allways change the "other part", the one which is not
being used by RT-thread. Like this:

struct {
	int valid_part;
	struct actual_data[2];
} my_data;

shm = (my_data *)mbuff_alloc(...)

Periodic RT-thread:
	pthread_wait_np();
	int valid_part = shm->valid_part;
	/* Read from and write to shm */
	a = shm->actual_data[valid_part].something;
	shm->actual_data[valid_part].something_else = b;
	...

User space:
	shm = (my_data *)mbuff_alloc(...)
	/* We are only allowed to change the non valid part! */
	int non_valid_part = !shm->valid_part;

	/* Change data in shm */
	shm->actual_data[non_valid_part].something = changed_value;
	...

	/* At the end change the pointer! */
	shm->valid_part = non_valid_part;


The main problem is the changing of this pointer (shm->valid_part). I
guess this should not be the problem on a 1-CPU machine, but on a SMP I
get lots of errors. 
What synchonizing mechanism should I use? Are mutexes or semaphores the
right answer for that? I am relatively new to mutexes and semaphores,
but is it safe to use mutexes, which might block the execution, in
RT-thread? I would only like to (efficiently = no CPU load) block the
user space thread, to wait for the RT-thread to finish, and then the
user space thread can safely change the pointer.

Is that possible and how? Is my approach with two identical structures
and a "valid pointer" right, or should I use some other approach?

Regards,
Ales