Evgenii Legotckoi
Evgenii Legotckoi28. Dezember 2018 09:09

Boost - Ausführen regelmäßiger Aufgaben mit boost::thread

Ich schlage vor, ein kleines Konsolenprogramm zu schreiben, das in regelmäßigen Abständen eine Aufgabe ausführt.

Beispielsweise startet das Programm und macht 10 Proben innerhalb von 10 Sekunden, während das Programm Informationen über die Anzahl der Countdowns in der Konsole anzeigt.

Das Programm wird wie folgt funktionieren.

Durchführen einer regelmäßigen Aufgabe in einer Konsolenanwendung


Projektstruktur

Das Projekt verwendet das CMake-Buildsystem, daher sieht die Projektstruktur wie folgt aus.

PeriodicTask-Projektstruktur

CMakeLists.txt

Hier ist die CMake-Standardkonfiguration zum Erstellen eines Projekts.

cmake_minimum_required (VERSION 3.8)

project(Periodic)

set(CMAKE_CXX_STANDARD 17)
set(Boost_USE_STATIC_LIBS ON)

find_package(Boost 1.68 REQUIRED COMPONENTS thread)

set(SOURCE_FILES
        Periodic/main.cpp
        Periodic/PeriodicTask.cpp)

SET(HEADER_FILES
        Periodic/PeriodicTask.h)

if(Boost_FOUND)
    include_directories(${Boost_INCLUDE_DIRS})
    add_executable(Periodic ${SOURCE_FILES} ${HEADER_FILES})
    target_link_libraries(Periodic ${Boost_LIBRARIES})
endif()

PeriodicTask.h

Die Header-Datei der periodischen Aufgabe.

Im einfachsten Fall benötigen wir zum Erstellen einer periodischen Aufgabenklasse:

  • Auslöseperiode
  • std::function-Objekt zum Speichern der Aufgabe
  • bool-Variable zum Stoppen und Starten der Aufgabe. In diesem Beispiel werden wir die Aufgabe nicht stoppen, aber wenn wir run / stop-Methoden hinzufügen, ist es durchaus möglich, dies zu implementieren.
  • boost::thread ist ein Thread, ohne den diese Funktionalität nicht implementiert werden kann
#pragma once

#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include <functional>
#include <atomic>

class PeriodicTask
{
public:
    explicit PeriodicTask(const boost::chrono::milliseconds &period, const std::function<void()> &func);

    virtual ~PeriodicTask();

private:
    boost::chrono::milliseconds m_period;   // Task period
    std::function<void()> m_func;           // The function that will perform the periodic task
    std::atomic<bool> m_running;            // A variable that indicates that the task is running, with the help of it you can stop the task in the future
    boost::thread m_thread;                 // Task thread
};

PeriodicTask.cpp

#include "PeriodicTask.h"

PeriodicTask::PeriodicTask(const boost::chrono::milliseconds &period, const std::function<void()> &func) :
    m_period(period),
    m_func(func),
    m_running(true)
{
    // Create a stream object to perform a periodic task.
    m_thread = boost::thread([this]
    {
        while (m_running)
        {
            // To perform a task with a specific period, immerse the stream in a dream after each task execution.
            boost::this_thread::sleep_for(m_period);
            if (m_running)
            {
                // perform the task
                m_func();
            }
        }
    });
}

PeriodicTask::~PeriodicTask()
{
    // When destroying an object with a periodic task
    m_running = false;
    // interrupt the flow, otherwise the program will not release system resources until the flow comes out of sleep
    // this is critical if the trigger period of the task is measured in tens of seconds and more
    m_thread.interrupt();
    m_thread.join();
}

main.cpp

Datei mit Hauptfunktion. Wenn wir ein periodisches Aufgabenobjekt erstellen, fügen wir eine Lambda-Funktion als Aufgabe hinzu, um so am einfachsten anzugeben, welche Arbeit zu erledigen ist.

#include "PeriodicTask.h" // We connect the class header file to perform periodic tasks.

#include <iostream>

int main(int argc, const char* argv[])
{
    std::cout << "Start program" << std::endl;
    int count = 0;
    // Create a periodic task with a period of 1 second
    PeriodicTask p(boost::chrono::seconds{ 1 }, [&count]() {
        // Display the counter and increment it by one.
        std::cout << count++ << std::endl;
    });

    // Stop the main program flow for 10 seconds so that the periodic task can work 10 times.
    boost::this_thread::sleep_for(boost::chrono::seconds{ 10 });
    std::cout << "End program" << std::endl;
    return 0;
}

Fazit

Abschließend lege ich dem Projekt das Archiv bei.

Periodic.zip Periodic.zip

Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

Kommentare

Nur autorisierte Benutzer können Kommentare posten.
Bitte Anmelden oder Registrieren
Letzte Kommentare
ИМ
Игорь Максимов5. Oktober 2024 07:51
Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas55. Juli 2024 11:02
QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssr8. Februar 2024 18:43
Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVA25. Dezember 2023 10:30
Boost - statisches Verknüpfen im CMake-Projekt unter Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
Jetzt im Forum diskutieren
J
JacobFib17. Oktober 2024 03:27
добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
JW
Jhon Wick1. Oktober 2024 15:52
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл Гусарев27. September 2024 09:09
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
Fynjy22. Juli 2024 04:15
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Folgen Sie uns in sozialen Netzwerken