简体   繁体   中英

Observer pattern - race condition

I would like to have your opinion about the following usage I find in OO application in C++, and whether you think it is correct or bad. We use observation pattern to imeplement model-view-controller as following:

 (Subject) (notify) (Listeners) 
 controller    --->  DB
               --->  Viewer

Is it correct to rely on the fact that DB is registed first to controller (before Viewer) and therefore will be updated before Viewer. This is critical because when Viewer get notified, it reads the information from DB (becuase it assumes that DB is already updated).

EDIT: controller and Viewer are threads while DB is not. controller always notify DB first and only then notify Viewer. The application works correctly. I Just thought that the registration of DB before Viewer is something ugly and wanted your opinion.

Thank you,

Ran

I would suggest another way of solving this issue, given your DB access layer has hooks for what is needed here.

Situation analysis: Given that a database update might fail, your view could do updates that are not needed. In case you have a distributed application, this can lead to serious performance problems.

The next thing is: Your database update might take longer than the notification of the view, so that the view reads old data when updated. (think this is what you see as race condition).

Solution: Place a hook on something like CommitFinished on your database access layer for the update of the view.

So a more robust way of doing this is:

1) Change => Controller => DB

2) DB commit finished (some DataChanged hook will do) => controller => View

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