In meiner Haupt-Funktion zu verlassen gibt es einige Objekte, die Arbeiten im Hintergrund zu tun, bis der destructor wie im folgenden Ausschnitt aufgerufen:C++ - Die beste Weg vom Haupt
#include <iostream>
class MyBackground {
public:
MyBackground()
{
m_workerThread = std::thread(&MyBackground::work, this);
}
~MyBackground()
{
g_exit = true;
workerThread.join();
}
private:
void work()
{
while(!m_exit);
}
private:
std::atomic<bool> m_exit{false};
std::thread m_workerThread;
};
int main(int argc, char* argv[])
{
MyBackground object;
// here ther's some async background work
return EXIT_SUCCESS;
// ~MyBackground -> here threads are stopped
}
Ich muß einen Weg Haupt zu blockieren, bis ein externes Signal tritt auf. Mein erster Versuch war etwas in der Art:
#include <csignal>
#include <iostream>
#include <thread>
using namespace std
atomic<bool> g_Exit{false};
void signalExit(int)
{
g_Exit = true;
}
int main(int argc, char* argv[])
{
signal(SIGINT, signalExit);
signal(SIGTERM, signalExit);
MyBackground object;
while (!g_Exit)
this_thread::sleep_for(chrono::seconds{1});
// here ther's some async background work
return EXIT_SUCCESS;
// ~MyBackground -> here threads are stopped
}
Aber ich bin mir nicht sicher, ob das gut funktioniert. Ich dachte, ist eine bessere Nutzung condition_variables
wie der folgende Ausschnitt:
#include <csignal>
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std
bool g_exitFlag = false;
condition_variable g_exitCondition;
mutex g_exitMutex;
using Lock = unique_lock<mutex>;
void signalExit(int)
{
Lock lock{g_exitMutex};
g_exitFlag = true;
g_exitCondition.notify_one();
}
int main(int argc, char* argv[])
{
signal(SIGINT, signalExit);
signal(SIGTERM, signalExit);
MyBackground object;
Lock lock{g_exitMutex};
g_exitCondition.wait(lock, [](){return g_exitFlag;});
// here ther's some async background work
return EXIT_SUCCESS;
// ~MyBackground -> here threads are stopped
}
Welche der besten Implementierungen korrekt ist. Sind sie richtig? Ich bin kein "Experte" in der Multithreading-Programmierung.
Was ist mit [sigwait] (http://man7.org/linux/man-pages/man3/sigwait.3.html)? –
Das ist gut, schade, das ist nicht auf Windows auch –
Ich denke, die Bedingung Variable Lösung ist besser, weil es Umfragen vermeidet. Das Polling ist eine nicht optimale Lösung, da es erfordert, dass die CPU regelmäßig aufwacht, und fügt dem Shutdown-Prozess eine unnötige Verzögerung hinzu. –