我可以使用指针赋值以安全的方式检测线程的开始吗?

时间:2014-09-16 15:02:35

标签: c++ multithreading pointers

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

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;
}

1 个答案:

答案 0 :(得分:1)

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