在C 中停止定期线程

Stopping a periodic thread-thing in c++

本文关键字:线程      更新时间:2023-10-16

,所以我拥有此函数,它的行为就像js中的setInterval函数。我在这里找到了。我目前正在尝试更改它,以便它可以停止。我不完全了解此代码的行为。

void setInterval(function<void(void)> func, unsigned int interval) {
  thread([func, interval]() {
    while (1) {
      auto x = chrono::steady_clock::now() + chrono::milliseconds(interval);
      func();
      this_thread::sleep_until(x);
    }
  }).detach();
}

我尝试过这样的尝试:

void setInterval(function<void(void)> func, unsigned int interval, bool &b) {
  thread([func, interval, *b]() {
    while (*b) {
      auto x = chrono::steady_clock::now() + chrono::milliseconds(interval);
      func();
      this_thread::sleep_until(x);
    }
  }).detach();
}

(这不会编译(,并且主要称其为:

bool B;
setInterval(myFunction,1000,B);

我期望,如果我将B变量更改为false,那么SetInterval函数中的线程会停止,但是我还没有设法实现我的目标。有任何IDEAD/建议吗?预先感谢您。

对不起,但是我没有找到比这更简单的设计。

您可以,将拥有线程的类和weak_ptr自身授予一类成为一个可呼叫可以安全看到的"持有人",因为可可即使对象被破坏,仍然存在。您不想要悬空的指针。

template<typename T>
struct IntervalRepeater {
    using CallableCopyable = T;
private:
    weak_ptr<IntervalRepeater<CallableCopyable>> holder;
    std::thread theThread;
    IntervalRepeater(unsigned int interval,
            CallableCopyable callable): callable(callable), interval(interval) {}
    void thread() {
        weak_ptr<IntervalRepeater<CallableCopyable>> holder = this->holder;
        theThread = std::thread([holder](){
            // Try to strongify the pointer, to make it survive this loop iteration,
            //    and ensure that this pointer is valid, if not valid, end the loop.
            while (shared_ptr<IntervalRepeater<CallableCopyable>> ptr = holder.lock()) {
                auto x = chrono::steady_clock::now() + chrono::milliseconds(ptr->interval);
                ptr->callable();
                this_thread::sleep_until(x);
            }
        });
    }
public:
    const CallableCopyable callable;
    const unsigned int interval;
    static shared_ptr<IntervalRepeater<T>> createIntervalRepeater(unsigned int interval,
            CallableCopyable callable) {
        std::shared_ptr<IntervalRepeater<CallableCopyable>> ret =
                shared_ptr<IntervalRepeater<CallableCopyable>>(
                        new IntervalRepeater<CallableCopyable>(interval, callable));
        ret->holder = ret;
        ret->thread();
        return ret;
    }
    ~IntervalRepeater() {
        // Detach the thread before it is released.
        theThread.detach();
    }
};
void beginItWaitThenDestruct() {
    auto repeater = IntervalRepeater<function<void()>>::createIntervalRepeater(
            1000, [](){ cout << "A secondn"; });
    std::this_thread::sleep_for(std::chrono::milliseconds(3700));
}
int main() {
    beginItWaitThenDestruct();
    // Wait for another 2.5 seconds, to test whether there is still an effect of the object
    //   or no.
    std::this_thread::sleep_for(std::chrono::milliseconds(2500));
    return 0;
}

C 不是JavaScript,但是C 可以以不同语言应用大多数编程范例。