简体   繁体   中英

Atomic operations on critical section data

Some part of shared memory modified in a critical section consists of considerable amount of data however only small portion of it is changed in a single pass (eg free memory pages bitmap). How to make sure that when program is interrupted/killed the data remains in a consistent state. Any suggestions other than having two copies (like a copy&swap in an example bellow or having some kind of rollback segment) ?

struct some_data{
  int a;
  int t[100000]; //large number of total data but a few bytes changed in a single pass (eg. free entries bitmap/tree).
};


short int active=0;
some_data section_data[2];

//---------------------------------------------------

//semaphore down

int inactive=active % 2;
section_data[inactive]=section_data[active];

// now, make changes to the section data (section_data[next_active])

active=inactive;

//semaphore up

You are looking for transactional consistency: a transaction occurs in whole, or not at all.

A common pattern is a journal, where you store the change you intend to make while you apply them. Anyone accessing the shared memory and detecting the crashed process (such as noticing that they somehow acquired the semaphore with a partially present journal), takes responsibility for replaying the journal before continuing.

You still have one race case, the actual writing of a bit signalling to all processes that there is, in fact, a journal to consume. However, that is a small enough body of information that you can send it through whatever channel you please, such as another semaphore or clever use of fences.

It's best if the journal is sufficiently independent of the state of the memory such that the repairing process can just start at the start of the journal and replay the whole thing. If you have to identify which entry in the journal is "next," then you need a whole lot more synchronization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM