gpt4 book ai didi

c++ - 以下 C++ 代码线程安全吗?

转载 作者:行者123 更新时间:2023-11-30 03:03:57 24 4
gpt4 key购买 nike

是下面的

int BlkArray::GetNthBlockA(unsigned int n, const Block *&pfb, int &maxIndex) const {
if (n + 1 >= (unsigned int)formattingPivots.GetCount()) return -1;
pfb = formattingPivots.GetNthBlckB(n);
maxIndex = formattingPivots.GetNthInt(n + 1) - 1;
return formattingPivots.GetNthInt(n);
}

线程安全考虑:

  1. formattingPivots.GetNthBlckB(n) , formattingPivots.GetNthInt(n + 1) , formattingPivots.GetNthInt(n)formattingPivots.GetCount()都是const方法。
  2. 我从 2 个线程调用 GetNthBlock(),当线程 1 调用并返回一个普通 block 时,我注意到线程 2 中的副作用。
  3. const Block *&pfb 从每个线程的 worker 方法中传递如下:

    int maxIndex;
    const Block *pfb = null;
    pStoredBlcks->GetNthBlockA(blockBreakIndex, pfb, maxIndex);

我很担心 const可能会在两个 worker 的 body 之间持续存在造成意想不到的影响。我 98% 的错误都来自上面的代码,但是由于多线程特有的问题,我无法确定。

我已经接近 24 小时的问题限制了,再说一件事,如果它可能有帮助的话。是static_cast<>线程安全? (傻吗?是的,但我写了很多年 C)我问是因为:

const Block *GetNthblckB(int n) const {
return static_cast<const Block*>(Blocks.GetAt(n));//Returns `Object`* without cast.
}

凌晨 3 点___谢谢小伙伴们的鼓励。我刚刚用 CritSecMonitor 包围了那个调用,但我仍然有副作用。如果不阅读 valgrind 手册,我最好了解一些 zz。

最佳答案

线程安全的第一事实:如果两个函数 f()g() 都是线程安全的,那么下面的函数不一定是线程安全的:

// h might not be thread-safe!
void h()
{
f(); // f is thread-safe
g(); // g is thread-safe
}

因此你将不得不根据GetNthBlckBGetNthInt等函数的内容来证明线程安全。我不知道这些方法是做什么的,所以我不知道它们是否是线程安全的(const 与它无关)。它看起来对我来说不是线程安全的。

关于c++ - 以下 C++ 代码线程安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9073766/

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