Hey, man!
I'll highlight a point in your code that should be causing the compilation error.
delete[] THREAD;
this delete is to delete 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 one would be to use delete THREAD
.
If you have questions about delete
and delete[]
access this link .
And how could I adapt the above code to work.
I would implement it as follows (you can modify it to suit 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 question author, I'll give you a brief explanation of some points in the code.
What is std :: unique_ptr?
contained in the header <memory>
o std::unique_ptr
(old _auto_ptr) is accompanied by two more "coleguinhas", they are std::shared_ptr
and std::weak_reference
and these guys are known as smart pointers (smart pointers).
The idea behind the pretty name is that the programmer does not have to worry about deallocating 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
to an object that will be shared between threads.
I advise you to study smart pointers.
Link to Portuguese: Smart Pointer - Introduction
What is atomic?
succinctly serves to synchronize threads when accessing a variable of this type.
if it does not make sense, I recommend that you study about thread
, mutex
and date races.
Read before you start your studies: Concurrent Programming x Parallel x Distributed
I hope to have helped!