I defined 3 read flag and 2 write flag.
int reader[3], writer[2]; // reader/writer flag
I define read lock function for the readers, the function wait until all the writer flags are off.
Then multilple reader can read concurrently, because it will not cause the reader get the wrong value.
I define write lock function for the writers, the function wait until all the read flags are off.
Then I defined additional write mutex to make the two writer write their value with out conflict with each other.
int mutex[2]; // maximum of 2 concurrent writer
int write_mutex(int id, int timeout) { //return -1 while timeout
int time = 0;
if( id = 1 ) {
mutex[0] = 1;
while(mutex[1]) {
time++;
if( time >= timeout ) {
mutex[0] = 0;
return -1;
}
}
} else if ( id = 2 ) {
mutex[1] = 1;
while(mutex[0]) {
time++;
if( time >= timeout ) {
mutex[1] = 0;
return -1;;
}
}
}
return 0;
}
The one with lower priority should wait if there is a conflict,
and the one with higher priority should hold the flag until others turn off their flag.
So the code with lower priority should always like this:
while(reader[i]) {
if( timeout++ < 1024 ) {
continue;
}
timeout = 0;
writer[ id - 1 ] = 0; // turn off flag
while( timeout++ < 1024 ) ;
writer[ id - 1 ] = 1; // turn on flag again
timeout = 0;
}
The simulation is done by using BACI, get the source here.