Object with its own thread and thread from inheritance? - c++

I have two objects
class Protocol : public UDPServer, private Thread { void loop(); ... };
class UDPServer : private Thread { void loop(); ... };
where Thread is a class which will call the object's loop-method in its own thread and where UDPServer will call a notify()-function in Protocol whenever it receives a new message.
Each of the two objects should run its own loop() during runtime (hence the two Thread-inheritances). According to this thread, this is not possible the way I wrote it.
I now wonder if I have to copy and rename the Thread-class to solve this problem or whether there's another workaround? I could probably solve this with two separate objects and circular inheritance but this would make the code somewhat more complex ...

Related

Communication between 2 threads C++ UNIX

I need your help with wxWidgets. I have 2 threads (1 wxTimer and 1 wxThread), I need communicate between this 2 threads. I have a class that contains methods to read/write variable in this class. (Share Memory with this object)
My problem is: I instanciate with "new" this class in one thread but I don't know that necessary in second thread. Because if instanciate too, adress of variable are differents and I need communicate so I need even value in variable :/
I know about need wxSemaphore to prevent error when to access same time.
Thanks you for your help !
EDIT: My code
So, I need make a link with my code. Thanks you for all ;)
It's my declaration for my wxTimer in my class: EvtFramePrincipal (IHM)
In .h
EvtFramePrincipal( wxWindow* parent );
#include <wx/timer.h>
wxTimer m_timer;
in .cpp -Constructor EvtFramePrincipal
EvtFramePrincipal::EvtFramePrincipal( wxWindow* parent )
:
FramePrincipal( parent ),m_timer(this)
{
Connect(wxID_ANY,wxEVT_TIMER,wxTimerEventHandler(EvtFramePrincipal::OnTimer),NULL,this);
m_timer.Start(250);
}
So I call OnTimer method every 250ms with this line.
For my second thread start from EvtFramePrincipal (IHM):
in .h EvtFramePrincipal
#include "../Client.h"
Client *ClientIdle;
in .cpp EvtFramePrincipal
ClientIdle= new Client();
ClientIdle->Run();
In .h Client (Thread)
class Client: public wxThread
public:
Client();
virtual void *Entry();
virtual void OnExit();
In .cpp Client (Thread)
Client::Client() : wxThread()
{
}
So here, no probleme, thread are ok ?
Now I need that this class that use like a messenger between my 2 threads.
#ifndef PARTAGE_H
#define PARTAGE_H
#include "wx/string.h"
#include <iostream>
using std::cout;
using std::endl;
class Partage
{
public:
Partage();
virtual ~Partage();
bool Return_Capteur_Aval()
{ return Etat_Capteur_Aval; }
bool Return_Capteur_Amont()
{ return Etat_Capteur_Amont; }
bool Return_Etat_Barriere()
{ return Etat_Barriere; }
bool Return_Ouverture()
{ return Demande_Ouverture; }
bool Return_Fermeture()
{ return Demande_Fermeture; }
bool Return_Appel()
{ return Appel_Gardien; }
void Set_Ouverture(bool Etat)
{ Demande_Ouverture=Etat; }
void Set_Fermeture(bool Etat)
{ Demande_Fermeture=Etat; }
void Set_Capteur_Aval(bool Etat)
{ Etat_Capteur_Aval=Etat; }
void Set_Capteur_Amont(bool Etat)
{ Etat_Capteur_Amont=Etat; }
void Set_Barriere(bool Etat)
{ Etat_Barriere=Etat; }
void Set_Appel(bool Etat)
{ Appel_Gardien=Etat; }
void Set_Code(wxString valeur_code)
{ Code=valeur_code; }
void Set_Badge(wxString numero_badge)
{ Badge=numero_badge; }
void Set_Message(wxString message)
{
Message_Affiche=wxT("");
Message_Affiche=message;
}
wxString Get_Message()
{
return Message_Affiche;
}
wxString Get_Code()
{ return Code; }
wxString Get_Badge()
{ return Badge; }
protected:
private:
bool Etat_Capteur_Aval;
bool Etat_Capteur_Amont;
bool Etat_Barriere;
bool Demande_Ouverture;
bool Demande_Fermeture;
bool Appel_Gardien;
wxString Code;
wxString Badge;
wxString Message_Affiche;
};
#endif // PARTAGE_H
So in my EvtFramePrincipal(wxTimer), I make a new for this class. But in other thread (wxThread), what I need to do to communicate ?
If difficult to understand so sorry :/
Then main thread should create first the shared variable. After it, you can create both threads and pass them a pointer to the shared variable.
So, both of them, know how interact with the shared variable. You need to implement a mutex or wxSemaphore in the methods of the shared variable.
You can use a singleton to get access to a central object.
Alternatively, create the central object before creating the threads and pass the reference to the central object to threads.
Use a mutex in the central object to prevent simultaneous access.
Creating one central object on each thread is not an option.
EDIT 1: Adding more details and examples
Let's start with some assumptions. The OP indicated that
I have 2 threads (1 wxTimer and 1 wxThread)
To tell the truth, I know very little of the wxWidgets framework, but there's always the documentation. So I can see that:
wxTimer provides a Timer that will execute the wxTimer::Notify() method when the timer expires. The documentation doesn't say anything about thread-execution (although there's a note A timer can only be used from the main thread which I'm not sure how to understand). I can guess that we should expect the Notify method will be executed in some event-loop or timer-loop thread or threads.
wxThread provides a model for Thread execution, that runs the wxThread::Entry() method. Running a wxThread object will actually create a thread that runs the Entry method.
So your problem is that you need same object to be accessible in both wxTimer::Notify() and wxThread::Entry() methods.
This object:
It's not one variable but a lot of that store in one class
e.g.
struct SharedData {
// NOTE: This is very simplistic.
// since the information here will be modified/read by
// multiple threads, it should be protected by one or more
// mutexes
// so probably a class with getter/setters will be better suited
// so that access with mutexes can be enforced within the class.
SharedData():var2(0) { }
std::string var1;
int var2;
};
of which you have somewhere an instance of that:
std::shared_ptr<SharedData> myData=std::make_shared<SharedData>();
or perhaps in pointer form or perhaps as a local variable or object attribute
Option 1: a shared reference
You're not really using wxTimer or wxThread, but classes that inherit from them (at least the wxThread::Entry() is pure virtual. In the case of wxTimer you could change the owner to a different wxEvtHandler that will receive the event, but you still need to provide an implementation.
So you can have
class MyTimer: public wxTimer {
public:
void Notify() {
// Your code goes here
// but it can access data through the local reference
}
void setData(const std::shared_ptr<SharedData> &data) {
mLocalReference=data
}
private:
std::shared_ptr<SharedData> mLocalReferece
};
That will need to be set:
MyTimer timer;
timer.setData(myData);
timer.StartOnece(10000); // wake me up in 10 secs.
Similarly for the Thread
class MyThread: public wxThread {
public:
void Entry() {
// Your code goes here
// but it can access data through the local reference
}
void setData(const std::shared_ptr<SharedData> &data) {
mLocalReference=data
}
private:
std::shared_ptr<SharedData> mLocalReferece
};
That will need to be set:
MyThread *thread=new MyThread();
thread->setData(myData);
thread->Run(); // threads starts running.
Option2 Using a singleton.
Sometimes you cannot modify MyThread or MyTimer... or it is too difficult to route the reference to myData to the thread or timer instances... or you're just too lazy or too busy to bother (beware of your technical debt!!!)
We can tweak the SharedData into:
struct SharedData {
std::string var1;
int var2;
static SharedData *instance() {
// NOTE that some mutexes are needed here
// to prevent the case where first initialization
// is executed simultaneously from different threads
// allocating two objects, one of them leaked.
if(!sInstance) {
sInstance=new SharedData();
}
return sInstance
}
private:
SharedData():var2(0) { } // Note we've made the constructor private
static SharedData *sInstance=0;
};
This object (because it only allows the creation of a single object) can be accessed from
either MyTimer::Notify() or MyThread::Entry() with
SharedData::instance()->var1;
Interlude: why Singletons are evil
(or why the easy solution might bite you in the future).
What is so bad about singletons?
Why Singletons are Evil
Singletons Are Evil
My main reasons are:
There's one and only one instance... and you might think that you only need one now, but who knows what the future will hold, you've taken an easy solution for a coding problem that has far reaching consequences architecturally and that might be difficult to revert.
It will not allow doing dependency injection (because the actual class is used in the accessing the object).
Still, I don't think is something to completely avoid. It has its uses, it can solve your problem and it might save your day.
Option 3. Some middle ground.
You could still organize your data around a central repository with methods to access different instances (or different implementations) of the data.
This central repository can be a singleton (it is really is central, common and unique), but is not the shared data, but what is used to retrieve the shared data, e.g. identified by some ID (that might be easier to share between the threads using option 1)
Something like:
CentralRepository::instance()->getDataById(sharedId)->var1;
EDIT 2: Comments after OP posted (more) code ;)
It seems that your object EvtFramePrincipal will execute both the timer call back and it will contain the ClientIdle pointer to a Client object (the thread)... I'd do:
Make the Client class contain a Portage attribute (a pointer or a smart pointer).
Make the EvtFramePrincipal contain a Portage attribute (a pointer or smart pointer). I guess this will have the lifecycle of the whole application, so the Portage object can share that lifecycle too.
Add Mutexes locking to all methods setting and getting in the Portage attribute, since it can be accessed from multiple threads.
After the Client object is instantiated set the reference to the Portage object that the EvtFramePrincipal contains.
Client can access Portage because we've set its reference when it was created. When the Entry method is run in its thread it will be able to access it.
EvtFramePrincipal can access the Portage (because it is one of its attributes), so the event handler for the timer event will be able to access it.

Waiting for an asynchronous method to finish

In my multi-threaded programs I often use an approach like shown below to synchronize access to data:
class MyAsyncClass
{
public: // public thread safe interface of MyAsyncClass
void start()
{
// add work to io_service
_ioServiceWork.reset(new boost::asio::io_service::work(_ioService));
// start io service
_ioServiceThread = boost::shared_ptr<boost::thread>(new boost::thread(boost::bind(&boost::asio::io_service::run, &_ioService)));
}
void stop()
{
_ioService.post(boost::bind(&MyAsyncClass::stop_internal, this));
// QUESTION:
// how do I wait for stop_internal to finish here?
// remove work
_ioServiceWork.reset();
// wait for the io_service to return from run()
if (_ioServiceThread && _ioServiceThread->joinable())
_ioServiceThread->join();
// allow subsequent calls to run()
_ioService.reset();
// delete thread
_ioServiceThread.reset();
}
void doSometing()
{
_ioService.post(boost::bind(&MyAsyncClass::doSometing_internal, this));
}
private: // internal handlers
void stop_internal()
{
_myMember = 0;
}
void doSomething_internal()
{
_myMember++;
}
private: // private variables
// io service and its thread
boost::asio::io_service _ioService;
boost::shared_ptr<boost::thread> _ioServiceThread;
// work object to prevent io service from running out of work
std::unique_ptr<boost::asio::io_service::work> _ioServiceWork;
// some member that should be modified only from _ioServiceThread
int _myMember;
};
The public interface of this class is thread-safe in the sense that its public methods can be called from any thread and boost::asio::io_service takes care that access to the private members of this class are synchronized. Therefore the public doSomething() does nothing but posting the actual work into the io_service.
The start() and stop() methods of MyAsyncClass obviously start and stop processing in MyAsyncClass. I want to be able to call MyAsyncClass::stop() from any thread and it should not return before the uninitialization of MyAsyncClass has finished.
Since in this particular case I need to modify one of my private members (that needs synchronized access) when stopping, I introduced a stop_internal() method which I post to the io_service from stop().
Now the question is: How can I wait for the execution of stop_internal() to finish inside stop()? Note that I cannot call stop_internal() directly because it would run in the wrong thread.
Edit:
It would be nice to have a solution that also works if MyAsyncClass::stop() is called from the _ioServiceThread, so that MyAsyncClass can also stop itself.
I just found a very nice solution myself:
Instead of removing work (resetting _ioServiceWork) in stop(), I do it at the end of stop_internal(). This means that _ioServiceThread->join() blocks until stop_internal() has finished - exactly what I want.
The nice thing about this solution is that it doesn't need any mutex or condition variable or stuff like this.

Alternative to postThreadMessage/peekmessage?

There's a (static) thread in my C++ application, frequently doing something. To exchange information between the thread and my application I use methods PostThreadMessage and PeekMessage.
Due to some reason I can't use these methods anymore but don't know a good alternative. Does anybody have an advice? I just want to exchange simple parameters.
There's no reason why you can't "exchange simple object with the main thread" as you said in a comment. A common pattern for sharing an instance of a class between threads is to do something like this:-
Declare your class with a static function that can be targeted by _beginthread and an instance function that does the work:
class CMyClass
{
// ... other class declarations ...
private:
static void __cdecl _ThreadInit(void *pParam); // thread initial function
void ThreadFunction(); // thread instance function
void StartThread(); // function to spawn a thread
// ... other class declarations ...
};
Define the functions something like this:
void CMyClass::StartThread()
{
// function to spawn a thread (pass a pointer to this instance)
_beginthread(CMyClass::_ThreadInit, 0, this);
}
void __cdecl CMyClass:_ThreadInit(void *pParam)
{
// thread initial function - delegate to instance
CMyClass *pInstance = (CMyClass*)pParam;
pInstance->ThreadFunction();
}
void CMyClass:ThreadFunction()
{
// thread instance function is running on another
// thread but has (hopefully synchronised) access
// to all of the member variables of the CMyClass
// that spawned it ....
}
Makes sense? The general idea is just to use the static function with a passed this pointer to connect back to a specific instance of the class.

wxHTTP & Threads

I have some problems with using wxHTTP inside a Thread. I have created below class which derive from wxThread to use wxHTTP.
class Thread : public wxThread {
private:
wxHTTP get;
public:
Thread()
{
}
~Thread()
{
}
virtual ExitCode Entry()
{
get.SetHeader(wxT("Content-Type"), wxT("text/html; charset=utf-8"));
get.Connect(wxT("www.mysite.com"));
get.SetTimeout(1);
wxInputStream *httpStream = get.GetInputStream(wxT("/script.php?name=aaa&text=blabla"));
wxDELETE(httpStream);
get.Close();
return 0;
}
};
I create this thread and run it (threads are created, ran and everything is fine with them). Unfortunately wxHTTP seems to doesn't work properly with threads (even my firewall doesn't ask me about connection). Is there any way to create wxHTTP connection inside a thread?
Here is the answer (as requested by #bluefeet)
wxHTTP inherits from wxSocketBase and in wxSocketBase we have this quote
When using wxSocket from multiple threads, even implicitly (e.g. by using wxFTP or wxHTTP in another thread) you must initialize the sockets from the main thread by calling Initialize() before creating the other ones.
See here for more explanation
Call
wxSocketBase::Initialize();
in your apps OnInit function
and wxurl/wxhttp functions should work from threads.

Encapsulated boost thread_group. Questions about ids and synchronization

I´m using a class that encapsulates a thread_group, and have some questions about it
class MyGroup{
private:
boost::this_thread::id _id;
boost::thread::thread_group group;
int abc;
//other attributes
public:
void foo();
};
In the class constructor, i launch N threads
for (size_t i=0;i<N;i++){
group.add(new boost::thread(boost::bind(&foo,this)));
}
void foo(){
_id = boost::this_thread::get_id();
//more code.
abc++ //needs to be sync?
}
So, here are my questions.
Do class attributes need to be synchronized?
Do every thread get a different id? For example, if I have
void bar(){
this->id_;
}
will this result in different ids for each thread, or the same for everyone?
Thanks in advance !
Yes, shared data access must be protected even if you use thread creation helpers as boost.
In the end they all will execute the same code at the same time, and there is nothing a library can do to put protection around a variable you own and you manage.
If this->_id prints the current thread id then yes, it will print different values while different threads access it.
I don't know what you are doing with this thread_group so this may or may not apply.
Yes, all threads will have a unique ID.
Yes, you need to protect your shared state, you can do this with synchronization or by 'avoiding' shared state by copying it or with message passing.
A relevant pattern here is the 'actor' pattern.
Essentially rather than just create threads in your constructor, consider either:
a) have a class that derives from boost::thread and store thread specific members there. you can then access the member variables in the thread which won't be global to the group.
e.g.
class MyThreadClass : public boost::thread
{
private:
int thread_local_int;
...
}
b) have a class that contains a boost::thread as a member variable
class MyThreadClass : public boost::thread
{
private:
int thread_local_int;
boost::thread t;
public:
boost::thread& GetThread()
{
return t;
}
...
}
store a collection of either of these in your MyGroup class and use thread_group::add_thread to put the threads in the thread_group.
You can now be incredibly thoughtful about which state is shared in the thread_group (it should be synchronized or read-only) and which state is local to your actor (or thread) and how it's accessible.
Note, I have a personal reluctance against using TLS because I like having some control and guarantees over lifetimes of objects and threads and I just find this easier when I don't use it; YMMV and its great for some uses...