这个问题似乎与线程和程序运行非常快有关。我有2个类,ThreadParentThreadChild,其中一个继承自另一个。 ThreadParent创建一个线程并运行函数func,将其声明为静态函数可避免指针问题。但是,我确实希望继承的类(例如ThreadChild)决定线程的确切功能,因此func调用虚函数Do

但是,当创建ThreadChild对象并立即运行时,线程在开始时会调用一次ThreadParent::Do,随后的所有调用均为ThreadChild::Do。有趣的是,当我稍等一会儿再调用Do时,它不会发生。

有没有比稍等片刻更好的解决方案了?更重要的是,为什么会发生这种情况?

这是一个小而完整的示例。它创建一个ThreadChild对象,该对象每200ms执行一次Do。程序在1s之后结束(等待回车)。

#include <iostream>
#include <windows.h>
#include <thread>

// The parent class
class ThreadParent {
protected:
    bool _loopThread; //setting this to false should end the thread
    std::thread _thread; //the thread

public:
    // Basic constructor
    ThreadParent(ThreadParent* child)
        : _loopThread(true),
        _thread(func, child, &_loopThread) {}

    // Stops the thread and waits for it to finish
    void StopThread() {
        _loopThread = false;
        _thread.join();
    }

protected:
    // The function the thread will be running (static because of pointer issues)
    static void func(ThreadParent* child, bool* loopThread) {
        //Sleep(10); //<- uncomment to solve the problem?
        while (*loopThread) {
            child->Do(); // Do is called every 200ms
            Sleep(200);
        }
    }
    // The function which is called repeatedly until _loopThread is set to false
    virtual void Do() {
        std::cout << "Parent call\n";
    }
};

// The child class
class ThreadChild : public ThreadParent {
public:
    // Basic constructor
    ThreadChild()
        : ThreadParent(this) {}

protected:
    // Redefines Do() with another message
    void Do() {
        std::cout << "Child call\n";
    }
};

// The program
int main() {
    ThreadChild thread;  // Create and run the thread
    Sleep(1000);         // Run the thread for 1s
    thread.StopThread(); // End it
    std::cout << "Press <enter> to terminate...";
    std::cin.get(); // Wait for user to end program
    return 0;
}

输出:
Parent call
Child call
Child call
Child call
Child call
Press <enter> to terminate...

最佳答案

在构造过程中,将在派生类之前构造基类子对象。在基类主体内部,动态类型实际上是基类的类型,因此动态函数分派(dispatch)(虚拟函数调用)将调用基类的相应函数。因此,根据时间的不同,您将看到两个函数都被调用。

为了解决这个问题,只需在构造完成后调用的第二个初始化函数中显式启动线程。

顺便说一句:static函数是一个红色鲱鱼,您不会避免任何错误。另外,创建线程层次结构通常是一个坏主意。而是,您的类实例代表任务或作业,这些任务或作业可能会或可能不会在单独的线程中执行。将这些对象紧密耦合到线程可能不是一个好主意。另外,将指针传递给基类构造函数的方式似乎很脆弱,因为在创建基本不应该存在的依赖项时会如此。

10-04 22:48
查看更多