gpt4 book ai didi

c++ - 我可以使用指针分配以安全的方式检测线程的开始吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:21:18 24 4
gpt4 key购买 nike

我很快编写了某种包装器以确保系统中的某些功能始终在定义的线程上下文中执行。为了使代码尽可能小,我简单地使用了一个指针赋值来检查线程是否已经启动。

void waitForStart() {
while (_handler == nullptr) {
msleep(100); // Sleep for 100ms;
}
msleep(100); // Sleep for 100ms to make sure the pointer is assigned
}

在我看来,这在任何情况下都应该有效。即使分配给 _handler 由于未知原因在 CPU 上分成两个操作。

我的假设正确吗?还是我错过了一个可能出错的案例?

引用一个更完整的系统示例。有 SystemThreadHandler 类:

class Handler {
public:
void doSomeWork() {
// things are executed here.
}
};

class Thread : public ThreadFromAFramework {
public:
Thread() : _handler(nullptr) {
}
void waitForStart() {
while (_handler == nullptr) {
msleep(100); // Sleep for 100ms;
}
msleep(100); // Sleep for 100ms to make sure the pointer is assigned
}
Handler* handler() const {
return _handler;
}
protected:
virtual void run() { // This method is executed as a new thread
_handler = new Handler();
exec(); // This will go into a event loop
delete _handler;
_handler = nullptr;
}
private:
Handler *_handler;
}

class System {
public:
System() {
_thread = new Thread();
_thread->start(); // Start the thread, this will call run() in the new thread
_thread->waitForStart(); // Make sure we can access the handler.
}
void doSomeWork() {
Handler *handler = _thread->handler();
// "Magically" call doSomeWork() in the context of the thread.
}
private:
Thread *_thread;
}

最佳答案

您错过了一个可能出错的案例。线程可能会在设置指针后 5 毫秒退出。如果没有同步,从两个线程访问任何变化的变量是不可靠的。

关于c++ - 我可以使用指针分配以安全的方式检测线程的开始吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25872243/

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