Using threads in classes

Asked

Viewed 209 times

-1

Hello, I have a problem regarding the use of threads. Once I use mingw to compile my projects, and this header is not implemented, I use this header to compile my projects. However, I am having some difficulties regarding the use of threads in classes.

class classe {
public:
    std::thread *THREAD = NULL;
    void Func() {}
    classe() {
        THREAD = new std::thread(Func);
    }
    ~classe() {
        delete THREAD;
    }
};

This above code does not compile and I would appreciate it if you would explain to me if it does not compile because of the library I am using or if it is a standard behavior of this feature and how I could adapt the above code to work.

P.S. I did not put the dynamic memory tag, because I believe that part is correct.

1 answer

1


And look at that! I will highlight a point in your code that must be causing the build error.

delete[] THREAD;

this delete is for deleting an array, see that THREAD is declared as std::thread *THREAD = NULL. delete[] would be used if a thread array was declared as std::thread *THREADS[], the correct would be to use delete THREAD.

if you have questions about delete and delete[] access this link.

and how I could adapt the above code for it to work.

i would implement as follows (you can modify to meet your needs)


#include <thread>
#include <memory>
#include <atomic>

class classe
{
public:
classe() : m_thread(nullptr){}

void start()
{
  m_running.store(true);
  m_thread.reset(new std::thread(&classe::worker, this));
}

// thread que invoca stop() será bloqueada até que worker tenha completado
void stop()
{
  m_running.store(false);
  m_thread->join(); //não esqueça dessa parte =) (se seu worker estiver em foreground)
}
private:

void worker()
{
  while(m_running.load())
  {
    // realize algum processo
  }
}

std::unique_ptr<std::thread> m_thread;
std::atomic<bool> m_running;
};  

DOUBTS
as requested by the author of the question, I will give a brief explanation on some points of the code.

what is Std::unique_ptr?

contained in the header <memory> the std::unique_ptr (former _auto_ptr) is accompanied by two more "little fellows", are they, std::shared_ptr and std::weak_reference and these guys are known as smart pointers (smart pointers).

the idea behind the beautiful name is that the programmer need not worry about dislocating dynamic memory.

example of std::shared_ptr


using SPtr = std::shared_ptr<int>;

{

  SPtr original(new int(10));

  original.use_count(); // retorna 1

  {

    SPtr segundo = original;

    original.use_count(); // retorna 2

    // "original" e "segundo" compartilham o mesmo ponteiro para um inteiro;

  } // fim do escopo, "segundo" será destruído na stack

  original.use_count(); // retorna 1

} // fim do escopo, original será destruido e ficando com use_count() igual a 0 e com isso o pointero será deletado automaticamente;

of course there are more benefits to using them, such as using shared_ptr for an Object that will be shared between threads. I advise you to study about smart pointers.

Link in English: Smart Pointer - Introduction

what is Atomic?

succinctly serves to synchronize threads when accessing a variable of this type. if it doesn’t make sense, I recommend that you study thread, mutex and date Races.

Read before starting your studies: Concurrent Programming x Parallel x Distributed

hope I’ve helped!

  • Thank you very much, it works! I have another question, as I adapt the code to the thread run only 1 time?

  • in the private worker() method; you can remove the loop (while(true){ }).

  • Just one more thing, I’ve been going over the code, but I can’t figure out how it works. Could you do me a favor and explain it to me?

  • Congratulations on being interested in learning how code works, few do. at what point are you having trouble understanding? Highlight and I will try to explain in the best way possible.

  • Hello! Thank you for your availability! I have a hard time understanding the unique_ptr and the atomic.

  • I edited my answer in a way that explains a little more about the code.

  • Thank you very much for the clarification and for your time!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.