Base:Handler()
,但如果届时将打电话Derived:Handler(
,右?
#include <thread>
#include <chrono>
#include <functional>
#include <iostream>
#include <mutex>
#include <condition_variable>
struct IPC
{
IPC() : t([&]{
std::unique_lock lk(mut);
cv.wait(lk, [&]{ return (bool)f; });
f();
}) {}
void SetHandler(std::function<void()> handler_) {
{
std::unique_lock lk(mut);
f = handler_;
}
cv.notify_all();
}
std::mutex mut;
std::condition_variable cv;
std::function<void()> f;
std::thread t;
};
struct Base {
Base() {
ipc.SetHandler([this]{ Handle(); });
// Maybe construction of Base takes some time.
// Removing this sleep makes the output of the program stabilize on "Derived".
std::this_thread::sleep_for(std::chrono::microseconds(10));
}
virtual void Handle() { std::cout << "Base" << std::endl; }
IPC ipc;
};
struct Derived : Base {
void Handle() override { std::cout << "Derived" << std::endl; }
};
int main()
{
Derived b;
// I only care about interaction with constructors so join here
// to delay destruction of b until the test is finished.
b.ipc.t.join();
}
Running this code multiple times in succession on my laptop produces randomly alternating outputs of "Base" and "Derived".
developer@WDX591VWD3:~$ g++-10 -std=c++20 hi.cpp -lpthread
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Derived
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Derived
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Derived
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Base
developer@WDX591VWD3:~$ ./a.out
Derived
developer@WDX591VWD3:~$
因此,我对问题持怀疑态度:这种不明确的行为吗? 我需要等待多长时间才能打电话给手,以便把衍生的班手提叫起来? 是否需要同步?