Pregunta de entrevista de Nuvoton

Given are two functions. One function writes to the shared memory using the function write_to_mem() One function reads from shared memory using the function read_from_mem() We also have a 8 bit variable sem. First function can set/clear only the first bit of sem (msb), indicating it just wrote to the mem. Second function can set/clear only the last bit of sem (lsb) indicating it finished reading from mem. Both functions can read both bits. The two functions might run on different processor with different frequencies. Processor 1 runs a code that call the first function in en endless loop Processor 2 runs a code that call the second function in en endless loop. I need to write the code in each processor such that the functions are synchronized.

Respuesta de la entrevista

Anónimo

8 de feb de 2018

The idea is to use sem as a state machine , so that when one write and one read from the mem is finished we go back to the original state. L | R 0 | 0 - starting state; 1 | 0 - writer finished writing 1 | 1 - reader finished reading from shared mem 0 | 1 - writer acknowledge that reader finished 0 | 0 - reader ack back the writer’s ack and we are back to starting state writer(){ while(true){ while(sem != 0x00){}//wait write_to_mem() set(sem,L); while(sem != 0x81){}//wait for readers to finish reading clear(sem,L) } } reader(){ while(true){ while(sem != 0x80){}//wait for writer to write read_from_mem(); set(sem,R); while(sem != 0x01){}//waite for writer’s ack clear(sem,R);//ack back to writer } }

1