Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 增压条件问题?_C++_Multithreading_Boost_Conditional Statements - Fatal编程技术网

C++ 增压条件问题?

C++ 增压条件问题?,c++,multithreading,boost,conditional-statements,C++,Multithreading,Boost,Conditional Statements,我对boost条件有一个问题,我在cpp类中有以下两个实例变量: boost::condition wait_answer_condition; boost::mutex wait_answer_mutex; 然后我有一个发送消息的方法,条件是: 方法1 boost::unique_lock<boost::mutex> lock(wait_answer_mutex) //do some work and send message /

我对boost条件有一个问题,我在cpp类中有以下两个实例变量:

boost::condition          wait_answer_condition;
boost::mutex              wait_answer_mutex;
然后我有一个发送消息的方法,条件是:

方法1

boost::unique_lock<boost::mutex>  lock(wait_answer_mutex)

//do some work and send message

//wait the result
wait_answer_condition.wait(lk);

//get the result
result = responseIdSyncMap[currentRequestID];
这两个方法在不同的线程中调用。问题是,当调用method2时,wait\u answer\u条件在调用“wait\u answer\u condition.notify\u one()”之前被释放,并且method1被唤醒而没有找到结果


有人对此有想法吗?

条件变量可能会被错误唤醒,而唤醒事件通常不会被存储(即,在任何人等待之前发出的唤醒会像无人聆听时在树林中击掌一样丢失)。因此,条件变量几乎总是在循环中使用:

bool is_answered = false;

// method1
boost::lock_guard<boost::mutex> lock( wait_answer_mutex );
while ( ! is_answered )
    wait_answer_condition.wait(lock);

// method2
boost::lock_guard<boost::mutex> lock( wait_answer_mutex );
is_answered = true;
wait_answer_condition.notify_one();
bool is\u responsed=false;
//方法1
boost::lock\u guard lock(等待\u应答\u互斥);
而(!有人回答)
等待应答条件。等待(锁定);
//方法2
boost::lock\u guard lock(等待\u应答\u互斥);
答案为真;
等待回答条件。通知一个();

条件变量可能会被错误唤醒,而唤醒事件通常不会被存储(即,在任何人等待之前发出的唤醒会像无人听到的木柴中的手拍一样丢失)。因此,条件变量几乎总是在循环中使用:

bool is_answered = false;

// method1
boost::lock_guard<boost::mutex> lock( wait_answer_mutex );
while ( ! is_answered )
    wait_answer_condition.wait(lock);

// method2
boost::lock_guard<boost::mutex> lock( wait_answer_mutex );
is_answered = true;
wait_answer_condition.notify_one();
bool is\u responsed=false;
//方法1
boost::lock\u guard lock(等待\u应答\u互斥);
而(!有人回答)
等待应答条件。等待(锁定);
//方法2
boost::lock\u guard lock(等待\u应答\u互斥);
答案为真;
等待回答条件。通知一个();

据我所知,我认为这种行为是故意的——你忘了锁定线程,所以我有一个sam结果。其原因是等待条件的虚假行为。参见thiton的回答。根据我的想法,这种行为是故意的-你忘记锁线了,所以我有一个结果。其原因是等待条件的虚假行为。参见thiton的答案。我将把你的最后一句话改为“因此,条件变量应始终在循环中使用”,另请参见(非boost)我将把你的最后一句话改为“因此,条件变量应始终在循环中使用”,另请参见(非boost)