mardi 17 avril 2018

Possible memory leak by continuously starting threads?

(First, sorry for my bad english.) I've programmed a little test code for my current project and I believe, that I've coded inefficient code: I want to start a new thread (which should run asynchronously to the main thread -> I use detach()), after the user have input three keys on it's keyboard. E.g. this thread should work five seconds and while the thread is working, the user can input more and more keys and always after three inputs a thread should start:

#include <iostream>
#include <cstdlib>
#include <thread>
#include <mutex>

using namespace std;

mutex m;
const int MAX_letters = 3;
int letters = MAX_letters;
thread st;

void send() {
    cout << "\nsending ... [START] ... " << this_thread::get_id() << "\n";
    this_thread::sleep_for(chrono::seconds(5));
    cout << "\nsending ... [END] ...   " << this_thread::get_id() << "\n";
}

int main() {

    while (true) {

        if (letters > 0) {
            system("PAUSE");
            --letters;
        } else {
            st = thread(send);
            st.detach();
            letters = MAX_letters;
        }

    }

    return 0;

}

The system("PAUSE") should simulate the key press...

Now my question: Is it ok to assign a new thread to st even though another is running?

Aucun commentaire:

Enregistrer un commentaire