多亏了Scott Meyers医生的书,第263页,我最近发现了condition_variable,所以我不得不按cppreference搜索它,以进行更多研究。
https://en.cppreference.com/w/cpp/thread/condition_variable
我对此有几个问题,因为我已经思考了好几天,但我仍然不明白。
我的问题是关于这段代码的:
// Manual unlocking is done before notifying, to avoid waking up
// the waiting thread only to block again (see notify_one for details)
lk.unlock();
cv.notify_one();
Run Code Online (Sandbox Code Playgroud)
1)我不了解cppreference的作者通过该注释和“等待中的线程,只能再次阻止”的含义,因为我什至都不知道如何翻译它,并且
2)它确切地表示哪个线程,特别是为什么。
3)它表示thread_worker还是主线程(父线程)?
4)他们选择这样做吗?
如果作者先通知然后手动解锁,那会发生什么变化?
我对Scott Meyers撰写的有效现代C ++的第270页有疑问。
他在第5/6行中写道:“唯一的妙处是,每个响应线程都需要引用共享状态的std :: shared_future的ITS OWN COPY ...”
我的问题是:为什么我们必须将的副本传递给std::shared_future每个线程中的每个lambda函数?鉴于先验,我认为通过引用传递它没有任何问题,以至于存在不同线程使用的唯一共享状态?
即使我通过了SF标准参考书,我也写了一个代码,改编自Scott Meyers博士的书,该代码有效。
因此,是否可以通过引用传递它?
#include <future>
#include <vector>
std::promise<void> p;
void react(){}
void detect()
{
auto sf = p.get_future().share();
std::vector<std::thread> vt;
int n=10;
for(int i=0;i < n; i++)
{
vt.emplace_back([sf]{sf.wait();
react();
});
}
p.set_value();
for(auto& t : vt)
t.join();
}
int main()
{
detect();
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我在C ++中有这个特殊的宏功能:
你能给我解释一下它是如何工作的:
#define EXAMPLE(obje) (::f(s, (obje), arg1, arg2, arg3))
Run Code Online (Sandbox Code Playgroud)
我有几个问题:
1)是什么::f意思?编译器在哪里搜索函数f?
2)是什么(obje)意思?为什么在括号之间?
我用第二个问题稍微修改了原始消息:
一位 C++ 专家建议我检查一下:https : //en.cppreference.com/w/cpp/numeric/bit_cast
更好地理解的表示double,memcpy和bit_cast (C++20)。
更具体地说,我试图理解为什么我们从代码中得到这个结果:
constexpr std::uint64_t u64v2 = 0x3fe9000000000000ull;
constexpr auto f64v2 = std::bit_cast<double>(u64v2);
Run Code Online (Sandbox Code Playgroud)
"f64::from_bits(0x3fe9000000000000u64) == 0.781250f64"
在此之前,我花时间研究了快速平方根求逆示例中提供的示例。
https://en.wikipedia.org/wiki/Fast_inverse_square_root#CITEREFGoldberg1991
我手动做了微积分,结果我终于意识到在这个特定情况下会发生什么,指数为 8 位,尾数为 23 位。
但是在我上面提到的作为 应用程序的示例中bit_cast,根据我的研究,指数似乎是 11 位,尾数是 52 位(双精度):https :
//en.wikipedia.org/wiki/Double-precision_floating -point_format
当我手工计算时,我发现
x = (1+Mx/L)*2^(Ex-B)
Run Code Online (Sandbox Code Playgroud)
和
L=2^52 and Ex = 2*(2^9- 1) with the notations of
Run Code Online (Sandbox Code Playgroud)
https://en.wikipedia.org/wiki/Fast_inverse_square_root#CITEREFGoldberg1991
而且我没有找到宣布的 0.781250 的结果。也许我选择的指数和尾数不正确。我不知道,但我真的很想知道会发生什么。
在此先感谢您的解释,以帮助您找到 0.781250
第二个问题:请您检查我在下面提出的问题作为对评论的回复,因为即使我对第一个例子也有挑战。提前致谢
我有以下代码来自“C++17 详解”一书:
union Superfloat{
float f;
int i;
}
int RawMantissa(Superfloat f){
return f.i & ((1< 23) -1);
}
int RawExponent(Superfloat f){
return (f.i >> 23)& 0xFF;
}
Run Code Online (Sandbox Code Playgroud)
在那段代码之后,Bartlomiej Filipek 先生写道:“然而,虽然上面的代码可能在 C99 中工作,但由于更严格的别名规则,它在 C++ 中是未定义的行为”。
我想更好地理解作者这句话的意思,因为我不明白。你能详细给我解释一下吗?
他给出了以下解释(但我需要更多解释):
C.183!...读取与写入时类型不同的联合成员是未定义的。这种双关语是不可见的,或者至少比使用命名的 >cast 更难发现.....
我也不明白这个解释,以及它如何帮助理解上面的代码是未定义的行为。
我将感谢您的深入解释