How to synchronize database access between a write stream and a read stream?

My program has two threads:

  • The main thread of execution that processes user input and creates queues for writing to the database
  • A utility thread that wakes up every second and flushes entries to the database

Inside the main thread, I sometimes need to do reads in the database. When this happens, performance is not important, but there is validity. (In an ideal world, I would read from the cache, not do it back and forth to the database, but put it aside for discussion.)

How can I make sure that the main thread sees the correct / resting database?

The standard mutex will not work, as I risk the main thread capturing the mutex before the data is dumped into the database. It will be a big race.

What I really want is some kind of mutex that allows the main thread to execute only after the mutex has been grabbed and released once. Is there such a thing? What is the best way to solve this problem?

UPDATE: after doing some additional research, I could use the Speed ​​up conditional variable to solve this problem. Either that, or just bite a bullet and cache my notes. Thanks for the feedback!

+6
c ++ multithreading mysql mutex
source share
3 answers

If you do not have more than one main thread of execution (i.e. the only thread that will push the entries into the workflow will be the same thread that will be read from the database), then you probably just have a simple variable / function “pending recordings” which you can check before sending reads and spin-locks or wait for a signal until the recordings are reset. It looks like you don’t need to do any locking or synchronization while recording, if you can just queue them for processing by the workflow.

Basically, as long as you are guaranteed that there is no write between checking the status of this “pending write” and actually reading it, then you don’t need to do anything too unusual.

+1
source share

Your proposed solution probably still leads to a race condition, because a “record” can appear at any time, even halfway through a new event standing in line.

The solution you can try is the state of the state of the atomic database: you do your processing and then compare it with the value of the state of the atom to make sure that you are reading from a database that is in a state that matches the start of reading. If it is different, you start all over again. It can be starved, but this is a separate problem.

Each time you change the database, you must compare and change the current value of the state of the atom, indicating a change.

+3
source share

Several solutions are possible:

  • Each thread opens its own d / b connection and uses it exclusively
  • Use one connection, but each thread has a mutex to access it.

I do not see a problem with the second choice. What harm is washed away when there is nothing to wash off?

+3
source share

All Articles