Updating the database only after waiting 20 seconds, so the maximum record can be obtained

Updating the database only after waiting 20 seconds, so the maximum record can be obtained.

When a student record is added from a tool (a tool that adds new data for a student to the database) it dispatches an event, that is, a RecordChangedEvent, and this tool can add many records at the same time.

Note: when the RecordChangedEvent is received I have to make a call to change.list to get the student record added

Let's say the first time when I added 200 records from tools and tools, send 200 RecordChangedEvent , but here I don't want to receive 200 events, and I delay for 20 seconds and ignore what comes during this delay.

After returning from the delay, I have to call change.list , which will add all the newly added entries that came when it was 20 seconds late, and add them all in one go.

My problem is I get 200 RecordChangedEvent and it is delayed by 200 * 20 seconds (which is bad). I want to ignore all events when it is on delay and when it comes back after delay, just get the update list from changed.list

Below is my approach (ineffective)

RecordChangedEvent(void)
{
    static bool lock = false;
    bool updateNewRecord = false;

    // delaying for 20 sec when first event received so that max record can be received
    if(!lock)  
    {
        lock = true;
        std::this_thread::sleep_for(std::chrono::seconds(20));
        updateNewRecord = true;  
    }
    if(updateNewRecord)
    {
        // adding after 20 sec delay changed.list will have all the updated received records within 20 seconds                
        AddedRecord(changed.list);       
        lock = false;
    }
}

      

+3


source to share


1 answer


You need multiple threads calling RecordChangedEvent

. If you only use one thread, that thread will block for 20 seconds before returning, receiving the next event, and then calling again RecordChangedEvent

(where it will wait another 20 seconds). Thus, you need at least one more thread to handle events while the first thread is sleeping.

Once you have multiple threads, you can still run into problems. Your variable is lock

not thread safe. There is a remote possibility that two threads can enter simultaneously if

with blocking. Also, there is no guarantee that a change lock

in one thread will be immediately visible in another. You should use the standard lock object instead.



Another source of problems is that the usage changed.list

here is unsynchronized as you are reading it (either to copy it to navigate to AddRecord

, or to AddRecord

if you pass it by reference) while elsewhere in your program another thread might be trying to add a new one item to list.

0


source







All Articles