Cannon run an overridden method - c++

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.

Related

Threading member function of multiple objects

I've got 2 class' where in the constructor of each spawns a thread which just prints hello world or goodbye universe. My goal is for the program to print out both hello world and goodbye universe at the same time. Problem is the program currently waits for the first thread to finish before starting the second. Its basically thread 1 is blocking the creation of threa2 until it finishes. What is the correct way for both threads to be executing at the same time?
My code is
#include <iostream>
#include "voltage.h"
#include <thread>
class MyClass final
{
private:
std::thread mythread;
void _ThreadMain()
{
int x = 1000;
while(x>0)
{
std::cout << "hello world " << x << std::endl;
x--;
}
};
public:
MyClass()
: mythread{}
{
mythread = std::thread{&MyClass::_ThreadMain, this};
mythread.join();
}
};
class MyClass2 final
{
private:
std::thread mythread;
void _ThreadMain()
{
int x = 1000;
while(x>0)
{
std::cout << "goodbye universe " << x << std::endl;
x--;
}
};
public:
MyClass2()
: mythread{}
{
mythread = std::thread{&MyClass2::_ThreadMain, this};
mythread.join();
}
};
int main(int argc, char *argv[])
{
MyClass *myClass = new MyClass();
MyClass2 *myClass2 = new MyClass2();
return 0;
}
My compile arguments are
g++ -g -march=armv6 -marm -I Sources/ main.cpp -L libraries/ -lyocto-static -lm -lpthread -lusb-1.0
Most of that is for other parts of the program i'm working on
Start threads in constructors and call join methods in destructors of your classes:
MyClass()
: mythread{} {
mythread = std::thread{&MyClass::_ThreadMain, this};
}
~MyClass() {
mythread.join();
}
MyClass2()
: mythread{} {
mythread = std::thread{&MyClass2::_ThreadMain, this};
}
~MyClass2() {
mythread.join();
}
but then you need to add in main the following lines
delete myClass; // wait until thread started in myClass ends
delete myClass2; // wait until thread started in muClass2 ends
to force destructors to be called.

Changes made within a member function cannot be seen outside its scope

I'm using a library which requires me to derive from a class it provides and then override a function.
However, I'm facing a strange situation where changes made within the member function are:
Temporary: they last only in the scope of the member function.
Non-persistent: In an iteration, the changes made in previous iterations are not visible.
For example, if I have a global int variable initialized to 0 which I increment in the member function, it's value pre-increment is 0 and 1 post-increment while within the member function, but always 0 outside the function's scope. Here is an example that demonstrates the problem:
#include <iostream>
#include <thread>
#include <gtkmm.h>
#include <xmlrpc-c/base.hpp>
#include <xmlrpc-c/registry.hpp>
#include <xmlrpc-c/server_abyss.hpp>
class TestWindow : public Gtk::Window {
public:
TestWindow();
// Called from worker thread
void notify(void (*callback)());
//Dispatcher handler
void on_notification_from_worker_thread();
//Data
Glib::Dispatcher m_Dispatcher;
//Callback functions
void (*on_notify_callback)();
};
class RpcWorker {
public:
RpcWorker(TestWindow* nw);
TestWindow* window;
RpcWorker* worker;
void start_thread ();
};
RpcWorker::RpcWorker(TestWindow* nw){
window = nw;
}
void foo (){
std::cout << "Foo called" << std::endl;
}
void bar (){
std::cout << "Bar called" << std::endl;
}
class testFunction : public xmlrpc_c::method {
public:
testFunction(TestWindow* nw, RpcWorker* worker);
TestWindow* window;
RpcWorker* worker;
void execute(xmlrpc_c::paramList const& paramList,
xmlrpc_c::value * const retvalP) {
window->notify(bar);
*retvalP = xmlrpc_c::value_int(0);
}
};
testFunction::testFunction(TestWindow* nw, RpcWorker* wk){
window = nw;
worker = wk;
}
void RpcWorker::start_thread() {
std::cout << "Thread started" << std::endl;
xmlrpc_c::registry myRegistry;
xmlrpc_c::methodPtr const testFunctionP(new testFunction(window, this));
myRegistry.addMethod("next.hideMinibuffer", testFunctionP);
xmlrpc_c::serverAbyss myAbyssServer (myRegistry, 8080, "/tmp/xmlrpc_log");
myAbyssServer.run();
}
TestWindow::TestWindow(){
m_Dispatcher.connect(sigc::mem_fun
(*this, &TestWindow::on_notification_from_worker_thread));
on_notify_callback = foo;
}
void TestWindow::notify(void (*callback)()) {
on_notify_callback = callback;
m_Dispatcher.emit();
}
void TestWindow::on_notification_from_worker_thread() {
on_notify_callback();
}
int main(int argc, char *argv[]){
auto app = Gtk::Application::create(argc, argv, "Test.Window");
TestWindow window;
RpcWorker worker = RpcWorker(&window);
std::thread* rpc_worker_thread = new std::thread(&RpcWorker::start_thread, &worker);
return app->run(window);
}
In this example, the on_notify_callback variable in the TestWindow class is initially set to point to function foo but later changed to function bar. Calling the function through the pointer while within the execute method immediately after changing it, function bar is invoked. However, once outside the scope of method execute, on_notify_callback points to foo.
What is causing this situation, and how do I fix it or work around it?

c++ virtual function and thread [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
here is my main.cpp code:
#include <opencv2/opencv.hpp>
using std::string;
#include "caffe_thread_learn.hpp"
class VideoCaptureTest : public InternalThread {
public:
string video;
explicit VideoCaptureTest(string v) : video(v) { StartInternalThread(); }
protected:
virtual void InternalThreadEntry();
};
void VideoCaptureTest::InternalThreadEntry(){
std::cout << "video child" << std::endl;
}
int main(){
InternalThread* vt = new VideoCaptureTest("/Users/zj-db0655/Documents/data/528100078_5768b1b1764438418.mp4");
delete vt;
return 0;
}
caffe_thread.cpp code:
#include "caffe_thread_learn.hpp"
InternalThread::~InternalThread() {
StopInternalThread();
}
bool InternalThread::is_started() const {
return thread_ && thread_->joinable();
}
bool InternalThread::must_stop() {
return thread_ && thread_->interruption_requested();
}
void InternalThread::StopInternalThread() {
if (is_started()) {
thread_->interrupt();
try {
thread_->join();
} catch (boost::thread_interrupted&) {
} catch (std::exception& e) {
std::cout << "Thread exception: " << e.what();
}
}
}
void InternalThread::StartInternalThread() {
thread_.reset(new boost::thread(&InternalThread::entry, this));
}
void InternalThread::entry() {
InternalThreadEntry();
}
caffe_thread.hpp code
#ifndef caffe_thread_learn_hpp
#define caffe_thread_learn_hpp
#include <stdio.h>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
namespace boost { class thread; }
class InternalThread {
public:
InternalThread() : thread_() {}
virtual ~InternalThread();
/**
* Caffe's thread local state will be initialized using the current
* thread values, e.g. device id, solver index etc. The random seed
* is initialized using caffe_rng_rand.
*/
void StartInternalThread();
/** Will not return until the internal thread has exited. */
void StopInternalThread();
bool is_started() const;
protected:
/* Implement this method in your subclass
with the code you want your thread to run. */
virtual void InternalThreadEntry() { std::cout << "parent" << std::endl; }
virtual void fun() {}
/* Should be tested when running loops to exit when requested. */
bool must_stop();
private:
void entry();
boost::shared_ptr<boost::thread> thread_;
};
#endif /* caffe_thread_learn_hpp */
actually, the output is:parant
However, i think output should be:video child. Because when StartInternalThread in VideoCaptureTest is called, it will new a thread with parameter (&InternalThread::entry, this), and I think this pointer to VideoCaptureTest and will call VideoCaptureTest's InternalThreadEntry which output video child. However, it output parent.
Thanks!
This is likely a timing issue between your threads. You create a new VideoCaptureTest object then immediately delete it before the thread created in StartInternalThread has a chance to run. When the destructor is called, the object will be torn down to an InternalThread object before the output has been generated.
Either put a sleep between your new/delete in main or wait for the thread to finish before destroying it.

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

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() ?

Destructor called before end of scope

The following program chrashes. But I don't really understand why. The boolean my_shared_resouce is in real life an asynchonous queue that eventually stops the loop inside of the thread via message passing.
However, the following program crashes because the destructor seems to be called multiple times. And the first time it does is long before the sleep in the main() finishes. If i remove the delete my_shared_resource; I can see the destructor is called three times...
However, following my current understanding the destructor should only be called when main() finishes.
#include <thread>
#include <chrono>
#include <iostream>
using namespace std;
class ThreadedClass {
public:
ThreadedClass() {
my_shared_resource = new bool(true);
}
virtual ~ThreadedClass() {
delete my_shared_resource;
cout << "destructor" << endl;
}
void operator()(){
loop();
}
void stop() {
*my_shared_resource = false;
}
private:
void loop() {
while (*my_shared_resource) {
// do some work
this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
bool* my_shared_resource;
};
int main(int argc, char** argv) {
ThreadedClass instance;
std::thread t(instance);
this_thread::sleep_for(std::chrono::milliseconds(1000));
cout << "Did some work in main thread." << endl;
instance.stop();
t.join();
return 0;
}
compiled with g++ (Ubuntu 4.8.4-2ubuntu1~14.04) 4.8.4
compiled as g++ --std=c++0x thread.cpp -pthread
Would someone please enlighten me what is wrong about this design.
When ThreadedClass gets copied both copies point to the same my_shared_resource, and both will delete it.
Use a std::shared_ptr<bool> instead:
class ThreadedClass {
public:
ThreadedClass() : shared_resource(new bool(true)) { }
virtual ~ThreadedClass() { }
void operator()() { loop(); }
void stop() { *shared_resource = false; }
private:
void loop() {
while (*shared_resource) {
// Do some work.
this_thread::sleep_for(std::chrono::milliseconds(1000));
}
}
std::shared_ptr<bool> shared_resource;
};
According to http://en.cppreference.com/w/cpp/thread/thread/thread
you are calling:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
which
Creates new std::thread object and associates it with a thread of execution. First the constructor copies/moves all arguments (both the function object f and all args...) to thread-accessible storage
Thus your my_shared_resourse pointer gets copied and shared between several copies of the thread object and gets destroyed in several places. Either define the appropriate copy constructor/assignment operator or use shared pointers.