mardi 28 août 2018

Declaring and starting a c++11 thread outside of main

I have a cpp file ("Plugin.cpp") which contains a small plugin that eventually gets linked into a much larger c++11 server project as a shared library.

It needs to start a thread and out of lazyness (it's a quick prototype) I simply declared and started it like so within Plugin.cpp:

#include <thread>

bool threadDone = false;

void myFunction() {
    while(!threadDone) {
    }
    // do stuff
}

std::thread myThread = std::thread(&myFunction);

// Called by server to stop tell plugin to cleanup.
void stopPlugin() {
    threadDone = true;
    myThreadDone.join();
    // ....
}

It seems like quite the anti-pattern to go starting threads as if the cpp file were a script file, but it works and doesn't seem to cause any problems when I run this code within the larger server project.

Without getting into the details of the larger project:

Can someone please detail what bad un-intended consequences may arise from doing this, as opposed to starting the thread in a more controlled manner from within an object or function?

My apologies if this is too obvious, I have not found this answer online and I have not coded in c++ recently so I am quite rusty. But it seems to me that something should eventually go very wrong.

Aucun commentaire:

Enregistrer un commentaire