gpt4 book ai didi

C++ 条件等待停止执行

转载 作者:行者123 更新时间:2023-11-28 06:11:02 25 4
gpt4 key购买 nike

我有以下类方法:

myclass::concurFnc(bool changingVar )
{
int i;
mIdMutex.lock();
i = mId++;
mIdMutex.unlock;

std::cout << "Try Waiting: " << i << std::endl;
std::mutex waitValidMutex;
std::unique_lock<std::mutex> l(waitValidMutex);
mNoOtherThreadDiffCompareVal.wait(l, [this, &changingVar]()
{
mSemMutex.lock();
bool result = false;
if(myclass::staticVar == changingVar)
{
std::cout << "Same var : " << changingVar << i << std::endl;
result = true;
--mSem;
} else if(mSem == 1)
{
std::cout << "Only one in crit section: " << i << std::endl;
--mSem;
myclass::staticVar = changingVar;
result = true;
} else
{
std::cout << "wait: " << i << std::endl;
result = false;
}
std::cout << "Sem is now " << mSem << std::endl;
mSemMutex.unlock();
return result;
});

//DO STUFF

mSemMutex.lock();
++mSem;
std::cout << "In the end sem is: " << mSem << std::endl;
mSemMutex.unlock();
mNoOtherThreadDiffCompareVal.notify_all();
}

//class Member Variables
std::mutex mSemMutex;
std::mutex mIdMutex;
std::condition_variable mNoOtherThreadDiffCompareVal;
int32_t mSem;
int32_t mId;

myclass::myclass() : mSem(1), mId(0)
{
}

void myclass::startThreads()
{
const int AMOUNT_OF_PROCESSES = 3
std::vector<std::shared_ptr<boost::thread> > processes;
for (size_t t_id = 0; t_id < AMOUNT_OF_PROCESSES; ++t_id)
{
bool changingVar = getVarSomewhere();
std::shared_ptr<boost::thread> thread_ptr(new boost::thread(&myclass::concurFnc, this, changingVar));
processes.push_back(thread_ptr);
}

for (size_t t_id = 0; t_id < AMOUNT_OF_PROCESSES; ++t_id) {
processes[t_id]->join();
}
}

如果 changingVar 与当前在//DO STUFF 中的所有其他调用者相同(或者如果它是唯一的),它应该允许进入//DO STUFF 部分该函数是从 boost::threads 中的函数并发调用的。

有时会发生执行停止的情况,因为它一直在等待,尽管 mSem 为 1 并且本应调用 notify_all()

执行停止前的输出是:

wait: 3248
Sem is now 0
Try Waiting: 3249
wait: 3249
Sem is now 0
In the end sem is: 1
Only one in crit section: 3249
Sem is now 0
Try Waiting: 3250
wait: 3250
Sem is now 0
In the end sem is: 1
Only one in crit section: 3250
Sem is now 0
In the end sem is: 1
Try Waiting: 3251
Same comp val : 0 of: 3251
Sem is now 0
.In the end sem is: 1

到目前为止我还不能真正重现它。

程序又开始工作了。也许是因为我将 gdb 附加到它,或者不知何故有一个巨大的延迟。

最佳答案

您对条件变量的使用模式很奇怪。

传递给条件变量的wait函数的互斥量应该总是保护你正在等待的条件的互斥量,这里好像是mSemMutex .

这是有道理的,因为为了检查等待的条件是否满足,您无论如何都需要锁定这个互斥体。考虑到这一点,您可能可以完全摆脱 waitValidMutex 并用 mSemMutex 替换它的所有用途。

另请注意,目前,由于 waitValidMutex 是本地互斥锁,您实际上是 risk undefined behavior when calling wait :

Calling this function if lock.mutex() is not the same mutex as the one used by all other threads that are currently waiting on the same condition variable is undefined behavior.

关于C++ 条件等待停止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31263689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com