我有两个进程A和B应该使用Windows 10上的Boost.Interprocess通过共享内存快速交换数据。我的问题:notify_all()
和wait()
之间的时间似乎很慢(定期15毫秒)。我结束了编写一个简单的应用程序来使用Windows下的QueryPerformanceCounter
来重现此问题,以获得准确的计时。 PerformanceCounter的init内部放在共享内存中,以便比较A和B之间的时间。
我使用这个放在共享内存中的常见结构:
namespace bi = boost::interprocess;
struct SharedStruct
{
double time; // Time to share between process A and B
// Sync objects
bi::interprocess_mutex mutex;
bi::interprocess_condition cond_data_ready;
volatile bool data_ready;
volatile bool exited;
// timing information for debug
long long counter_start;
double pc_freq;
};
第一个进程创建共享内存,初始化时序信息,然后运行此函数:
// Process A (producer)
void Run()
{
for (int i = 0; i != 10; ++i)
{
Sleep(1000); // Sleep 1 sec to simulate acquiring data
// In my real code, this is not a Sleep but a WaitForMultipleObjects() call
double counter;
{
bi::scoped_lock<mutex_type> lock(m_main_struct->mutex);
double counter = GetCounter();
m_main_struct->time = counter;
m_main_struct->data_ready = true;
}
m_main_struct->cond_data_ready.notify_all();
}
bi::scoped_lock<mutex_type> lock(m_main_struct->mutex);
m_main_struct->exited = true;
m_main_struct->cond_data_ready.notify_all();
}
进程B打开已存在的共享内存并读取数据。
// Process B : read and print timestamps diff
void Run()
{
bi::scoped_lock<mutex_type> lock(m_main_struct->mutex);
while (!m_main_struct->exited)
{
m_main_struct->cond_data_ready.wait(lock);
if(m_main_struct->data_ready)
{
m_main_struct->data_ready = false;
double counter = GetCounter();
double diff = counter - m_main_struct->time;
std::cout << boost::lexical_cast<std::string>(counter) << " and the diff is : " << diff << std::endl;
}
}
std::cout << "Exiting..." << std::endl;
}
输出类似于:
3011.8175661852633 and the diff is : 0.0160456
4044.836078038385 and the diff is : 15.6379
5061.9643649653617 and the diff is : 15.5186
6079.200594853236 and the diff is : 15.6448
7075.2902152258657 and the diff is : 0.0218803
8119.8910797177004 and the diff is : 26.4905
9099.8308285825678 and the diff is : 0.0379259
10122.977664923899 and the diff is : 0.0393846
11140.647854688354 and the diff is : 0.0145869
12158.33992478272 and the diff is : 0.0237037
Exiting...
有时,notify_all()
和wait()
之间的时间小于1毫秒(这很好),但有时大约是15毫秒,这是我认为的太多了。如果我使用Windows事件通知/等待,则此问题消失(约0.05毫秒)。
这是正常的吗?有什么想法吗?