Will :: condition improve performance?

We have an application with multiple threads. In the current implementation, at start, thread1 is created and wakes up periodically (every second or so, it is configured) to check the disk for potentially saved files. These files are saved by another thread, thread2 . This launch of thread1 and its periodic awakening can slow down the application.

Now we have the opportunity to use the boost :: condition variable to put thread1 in the lock until thread2 notifies it. In doing so, you must create a flag to avoid unnecessary notification from thread2 , and this flag must be synchronized and checked with high frequency (hundreds in a few seconds) on thread2 . Or thread1 will be notified every time a recording occurs.

My questions are here:

  • In the implementation of boost :: condition, thread1 you still need to wake up often to check the flag, and the difference is that the implementation is hidden from us, but it actually does. I'm right? Does a similar API in Windows and Java do the same?

  • What happens if a thread is notified often many times, even if it is not in a wait state?

  • In my case, will this improve overall performance by switching to boost :: condition implementation? My opinion is no.

+4
source share
2 answers

, thread1 , :

//thread1 - consumer
void thread1() {
    boost::scoped_lock lock(sharedMutex);
    // shared mutex locked, no events can be sent now
    while(1) {
        // check for files written by thread2
        sharedCond.wait( lock ); // this action unlocks the shared mutex, events can be sent now
    }
}

//thread2 - producer
void thread2() {
    boost::scoped_lock lock(sharedMutex); // will wait here until thread 1 starts waiting
    // write files
    sharedCond.notify_one();
}

3. : , . 1 , / ( 1 ), , , - . thread1, 1 , . , thread2 - , , - , , thread1 .

+1

- , :: condition. thread1() flag:

#include <mutex>
#include <condition_variable>
#include <thread>

std::mutex mut;
bool flag;
std::condition_variable data_cond;

void thread2()
{
    //here, writing to a file
    std::lock_guard<std::mutex> lk(mut);
    flag = true;  //a new file is saved
    data_cond.notify_one();
}

void thread1()
{
    while(true)
    {
        std::unique_lock<std::mutex> lk(mut);
        data_cond.wait(lk,[]{return flag;});
        //here, processing the file
        flag = false;
        lk.unlock();
    }
}

++ 11, 4_1 : ++ Concurrency , 4

0

All Articles