In briefly: I'm working on a little chat program just for fun.
I am using threads to control two main parts of the application. I am making a socket controller class based on the following design:
//this is a "main.cpp example" for the design
std::mutex mtx;
class AThreadedClass
{
public:
AThreadedClass()
{
running = true;
value1 = 0;
value2 = 0;
value3 = 0;
}
//first method which is used for threads
void run()
{
{
std::lock_guard<std::mutex> lck(mtx);
value1 = 0; value2 = 0; value3 = 0;
}
while (running)
{
{
std::lock_guard<std::mutex> lck(mtx);
value1 += 2; value2 +=1; value3 -= 1;
if (value1 > 1000000)
{
running = false;
}
}
}
}
//second method used as thread
//this will possible be just a data
//retrieving function, not necessarly
//used as thread
void writeOut()
{
while(running)
{
std::lock_guard<std::mutex> lck(mtx);
std::cout << value1 << ';' << value2 << ';' << value3 << '\n';
}
}
private:
int value1, value2, value3;
std::atomic<bool> running;
};
int main()
{
AThreadedClass class1;
std::thread t1(&AThreadedClass::run, &class1);
std::thread t2(&AThreadedClass::writeOut, &class1);
t1.join();
t2.join();
std::cout << "Threads finished successfully!\n";
return 0;
}
So, here are the things I was wondering about:
- Is this a good way to manage things? (I mean, using classes and their member functions for threads could be a stupid idea :/)
- Are there possible deadlocks, when I am mixing
std::atomic
withstd::mutex
like in the example? (So far it worked perfectly for me)
And if I didn't notice an existing question about this, please point to it.