c++ meyers singleton containing std::thread can't join - c++

i have a problem with the scott meyers singleton. my singleton contains a thread which shall get joined in the singleton destructor, but the join() never returns.
When i join the thread before application exit everything works fine. am i missing something? following my code:
#include <thread>
#include <atomic>
#include <iostream>
#include <chrono>
class Singleton
{
public:
static Singleton& get_instance()
{
static Singleton instance;
return instance;
}
void stop()
{
run = false;
if (t.joinable())
t.join();
}
private:
Singleton() { t = std::thread{ &Singleton::f, this }; }
~Singleton()
{
std::cout << "dtor start" << std::endl;
stop();
std::cout << "dtor end" << std::endl; // <-- never gets called. programm freezes here
}
void f()
{
while (run)
{
// do work ...
std::cout << "i do some work..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
std::atomic<bool> run = true;
std::thread t;
};
int _tmain(int argc, _TCHAR* argv[])
{
auto& s = Singleton::get_instance();
std::this_thread::sleep_for(std::chrono::seconds(2));
s.stop(); // <-- works fine
return 0;
}
So as i mentioned: with the call to s.stop(); it works fine but without it "freezes".
Is there a way to prevent the call to stop() ?

Related

How do I make a seperate thread inside a class?

I have a class foo and i put inside a member function a thread object. And i tried to initialize it like this std::thread mythread(&foo::myprint, this); inside another function. My problem is that I get the same thread::get_id with a different function foo::mycount that i need to count something. Both myprint and mycount uses this_thread::sleep_for but they don't sleep separately (something that i want to happen). I follow you up with some code example
class foo
{
void func()
{
std::thread mythread(&foo::myprint, this);
mythread.join();
}
void myprint()
{
sleep_for(1s);
cout << count << endl;
}
void mycount()
{
sleep_for(1ms);
count++;
cout << count << endl;
}
};
void main()
{
foo obj;
while(1)
{
obj.func();
obj.mycount();
}
}
I also tried putting mycount in another function with a thread object, and I don't if std::call_once affected anything, cause i used it inside the mycount function. I expected a different get_id for different functions.
Here is an example with a lambda function to start an asynchronous process.
And using std::future for synchronizing the destructor of your class with the background thread (which is counting numbers in this example).
#include <iostream>
#include <future>
#include <thread>
#include <chrono>
// dont do "using namespace std"
using namespace std::chrono_literals;
class foo
{
public:
foo() = default;
~foo()
{
// destructor of m_future will synchronize destruction with execution of the thread (waits for it to finish)
}
void func()
{
m_future = std::async(std::launch::async, [=] { myprint(); });
}
void myprint()
{
for (std::size_t n = 0; n < 5; ++n)
{
std::this_thread::sleep_for(1s);
std::cout << n << " ";
}
std::cout << "\n";
}
private:
std::future<void> m_future;
};
int main()
{
foo obj;
obj.func(); // start thread
return 0;
}

How to make destructor wait until other thread's job complete?

I have one main thread that will send an async job to the task queue on the other thread. And this main thread can trigger a destroy action at any time, which could cause the program to crash in the async task, a piece of very much simplified code like this:
class Bomb {
public:
int trigger;
mutex my_mutex;
};
void f1(Bomb *b) {
lock_guard<std::mutex> lock(b->my_mutex); //won't work! Maybe b have been destructed!
sleep(1);
cout<<"wake up.."<<b->trigger<<"..."<<endl;
}
int main()
{
Bomb *b = new Bomb();
b->trigger = 1;
thread t1(f1, b);
sleep(1);
//lock here won't work
delete b;//in actual case it is triggered by outside users
t1.join();
return 0;
}
The lock in f1 won't work since the destructor can be called first and trying to read mutex will crash. Put lock in destructor or before the delete also won't work for the same reason.
So is there any better way in this situation? Do I have to put mutex in the global scope and inside destructor to solve the issue?
In code, my comment looks like this :
#include <future>
#include <mutex>
#include <iostream>
#include <chrono>
#include <thread>
// do not use : using namespace std;
class Bomb
{
public:
void f1()
{
m_future = std::async(std::launch::async,[this]
{
async_f1();
});
}
private:
void async_f1()
{
using namespace std::chrono_literals;
std::lock_guard<std::mutex> lock{ m_mtx };
std::cout << "wake up..\n";
std::this_thread::sleep_for(1s);
std::cout << "thread done.\n";
}
std::future<void> m_future;
std::mutex m_mtx;
};
int main()
{
{
std::cout << "Creating bomb\n";
Bomb b; // no need to use unecessary new
b.f1();
}
std::cout << "Bomb destructed\n";
return 0;
}

asio::io_service::run doesnt return after boost::asio::io_service::work is destroyed

As title says I'm having this problem when I can't understand why this thread
never stops running even after Client's destructor destroys asio::io_service::work variable
When I'm running this program output is always like this
Anyone sees what I'm missing here?
#include <boost/asio.hpp>
#include <thread>
#include <atomic>
#include <memory>
using namespace boost;
class Client{
public:
Client(const Client& other) = delete;
Client()
{
m_work.reset(new boost::asio::io_service::work(m_ios));
m_thread.reset(new std::thread([this]()
{
m_ios.run();
}));
}
~Client(){ close(); }
private:
void close();
asio::io_service m_ios;
std::unique_ptr<boost::asio::io_service::work> m_work;
std::unique_ptr<std::thread> m_thread;
};
void Client::close()
{
m_work.reset(nullptr);
if(m_thread->joinable())
{
std::cout << "before joining thread" << std::endl;
m_thread->join();
std::cout << "after joining thread" << std::endl;
}
}
int main()
{
{
Client client;
}
return 0;
}
EDIT
After StPiere comments I changed code to this and it worked :)
class Client{
public:
Client(const Client& other) = delete;
Client()
{
m_work.reset(new boost::asio::executor_work_guard<boost::asio::io_context::executor_type>(boost::asio::make_work_guard(m_ios)));
m_thread.reset(new std::thread([this]()
{
m_ios.run();
}));
}
~Client(){ close(); }
private:
void close();
asio::io_context m_ios;
std::unique_ptr<boost::asio::executor_work_guard<boost::asio::io_context::executor_type>> m_work;
std::unique_ptr<std::thread> m_thread;
};
I cannot reproduce the error on either compiler.
Here example for gcc 9.3 and boost 1.73
Normally the work destructor will use something like InterLockedDecrement on windows to decrement the number of outstanding works.
It looks like some compiler or io_service/work implementation issue.
As stated in comments, io_service and io_service::work are deprecated in terms of io_context and executor_work_guard.

Cannon run an overridden method

There is a class "Mario". This one has an virtual method: void mission(). I want override this method and run it from base class code in parallel.
But output of the following code is:
Mario works hard
LOL
Code:
#include <iostream>
#include <thread>
class Mario
{
std::thread workingField;
bool hasStarted = false;
public:
virtual void mission()
{
std::cout << "LOL" << std::endl;
}
void startMission()
{
if (!hasStarted)
{
workingField = std::thread([this]() {
this->mission();
});
hasStarted = true;
}
}
virtual ~Mario()
{
if (hasStarted)
{
workingField.join();
}
}
};
class MarioWorker : public Mario
{
public:
void mission() override final
{
std::cout << "Mario works hard" << std::endl;
}
};
int main(int argc, char *argv[])
{
MarioWorker mw;
mw.mission();
mw.startMission();
}
How can I get a double line "Mario works hard", when one of them is executed in another thread?
In other words how a base class can execute an overridden method in parallel?
I'm using GCC 9.3
The problem is, the main thread is too fast. Your main method ends, the deconstruction of mw starts, MarioWorker gets destructed and once it starts destructing the Mario it joins the thread. The thread never sees the MarioWorker as it was already destructed, all it sees is the Mario.

Accessing counter from two threads

I have a counter that is being incremented from one thread. In the main thread, I basically print it out by calling data member of a class. In the below code, nothing is being printed out.
#include <iostream>
#include <thread>
#include <windows.h>
#include <mutex>
std::mutex mut;
class Foo
{
public:
Foo(const int& m) : m_delay(m), m_count(0)
{}
void update()
{
std::cout << "count: " << this->m_count << std::endl;
}
void operator()()
{
while (true){
mut.lock();
m_count++;
mut.unlock();
Sleep(m_delay);
}
}
private:
int m_delay;
int m_count;
};
Foo *obj = new Foo(200);
int main()
{
std::thread *t = new std::thread(*obj);
t->join();
while(true)
{
obj->update();
Sleep(10);
}
return 0;
}
The problem with the original code is that this copies the Foo object:
std::thread *t = new std::thread(*obj);
That means that the increments happen to the copy, and so the value in the original Foo never changes, and so when main prints it out (if you move the misplaced join()) the value is always the same.
A solution is to use a reference not a copy:
std::thread *t = new std::thread(std::ref(*obj));
You also need to protect the read of the variable by the mutex (or use std::atomic<int> for the counter) to avoid undefined behaviour caused by concurrently reading and writing a non-atomic variable.
You should also stop using mut.lock() and mut.unlock() directly, use a scoped lock instead.
There's also no need to create things on the heap unnecessarily, overusing new is a bad habit of people who learnt Java and C# first.
You can also make the code portable by replacing the Windows-specific Sleep call with standard C++.
A correct version would be:
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
std::mutex mut;
class Foo
{
public:
Foo(std::chrono::milliseconds m) : m_delay(m), m_count(0)
{}
void update()
{
int count = 0;
{
std::lock_guard<std::mutex> lock(mut);
count = m_count;
}
std::cout << "count: " << count << std::endl;
}
void operator()()
{
while (true)
{
{
std::lock_guard<std::mutex> lock(mut);
m_count++;
}
std::this_thread::sleep_for(m_delay);
}
}
private:
std::chrono::milliseconds m_delay;
int m_count;
};
Foo obj(std::chrono::milliseconds(200));
int main()
{
std::thread t(std::ref(obj));
while(true)
{
obj.update();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
t.join();
return 0;
}
Alternatively, use an atomic variable so you don't need the mutex:
#include <iostream>
#include <thread>
#include <chrono>
#include <atomic>
class Foo
{
public:
Foo(std::chrono::milliseconds m) : m_delay(m), m_count(0)
{}
void update()
{
std::cout << "count: " << m_count << std::endl;
}
void operator()()
{
while (true)
{
m_count++;
std::this_thread::sleep_for(m_delay);
}
}
private:
std::chrono::milliseconds m_delay;
std::atomic<int> m_count;
};
Foo obj(std::chrono::milliseconds(200));
int main()
{
std::thread t(std::ref(obj));
while(true)
{
obj.update();
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
t.join();
return 0;
}