Reputation: 31
Hey :) it is not really a practical example. It's just to test some things.
The threads are supposed to represent independent input objects which randomly create data and send this data to another receiver object.
My problem is that i want them to create data for an infinite time. But as i start the first thread it gets stuck cause of the while loop.
How is it possible to start multiple infinite threads?
#pragma once
#include <iostream>
#include <thread>
class A
{
public:
A() : m_ID(-1) {}
A(int _ID) : m_ID(_ID) {}
~A() {}
public:
void DoWork()
{
std::thread T(&A::Work, this);
T.join();
}
private:
void Work()
{
while (true)
{
// do stuff
std::cout << m_ID << "\n";
}
}
private:
int m_ID;
};
#include "A.h"
static const unsigned int s_NumberOfObjects = 5;
void main()
{
A As[s_NumberOfObjects];
for (size_t i = 0; i < s_NumberOfObjects; i++)
{
As[i] = A(i);
}
for (size_t i = 0; i < s_NumberOfObjects; i++)
{
As[i].DoWork();
}
}
Upvotes: 0
Views: 69
Reputation: 26496
make the thread a member variable, and move the join
function to A
destructor
class A{
/* ... */
public:
~A() { m_Worker.join(); }
/*...*/
void DoWork()
{
m_Worker = std::thread(&A::Work, this);
}
private:
int m_ID;
std::thread m_Worker;
};
using detach
is highly discouraged as you loose all track for the thread and you have no way to tell it to shut down cleanly when the application terminates.
Upvotes: 1