I am trying to use my own C++ class to interact with a COM library that is STA.
The problem we are trying to solve is that a third party application has the STA attribute set to it. The application then creates the C++ service we created and other services (in our case a WCF service) are modifying elements in the service created by the third party STA attribute application. In essence we have Thread1 coming from STA application who creates the service, then Thread2...N coming from WCF which is not in a STA thread state manipulating data held in the service. The STA application doesn't see the changed data and acts as though nothing happened.
So in order to fix it, I am thinking that I have to ensure that all operations contained in my service need to be guaranteed to run on the same thread. The question I have is how to achieve that.
I will show an example of our current code.
Current Service (every method needs to be called on the same thread that it was initially created on)
MyService::MyService()
{
// creates some objects and maybe some other initializing
// Whatever thread (the STA application in this case) this was
// created on needs to be used on all methods, how?
}
ObjectA MyService::GetObject()
{
return anObject;
}
ObjectB MyService::CreateObjectB()
{
// Do some tasks that eventually create object
object = new ObjectB();
return object;
}
void MyService::SomeVoidFunction()
{
// Do some work
}
I am not sure if I can take advantage of the TPL and do this, or do I need to use ThreadPools or something like that?
Related
I have a problem, I'm connecting my program to the data base with an Api, to do this I use the network and webkit webkitwidgets funtions in Qt. I have been able to do this without any problem.
The think it's that I have to call some funtions in the api class from different threads.
Firts I try passing the api object to the Qthread class, but I'm getting this error:
#QObject: Cannot create children for a parent that is in a different thread.
(Parent is SerialPort(0x24a1738), parent's thread is QThread(0x24a1770), current thread is QThread(0x18a8b0)
So I try ussing signals ans slots, it work with the firts function I use, a funtion to create what a call in my data base a log, but when I try to close the log, so I can send the information needed. I get this error:
QEventLoop::exec: instance xxxxxx has already called exec()
What is the best way to work with Threads to avoid this problems ??
You haven't provided any code, only error messages. Since I have to guess, I'll say that you're creating a QObject-derived worker object and using the QObject::moveToThread method to change its thread affinity. The problem in this case is that you've already given the worker object a parent. You can't use moveToThread on an object that already has a parent. So, don't set the parent of your worker object when you create it and you should be good-to-go.
As others users have commented, you will need to use signals & slots to initiate queries, etc. in your worker object. Qt will handle synchronization issues via the thread's event loop, so you don't have to worry about mutex locking, etc (as long as you use only sig/slot to invoke methods and get output values from the worker object).
Don't forget to call QThread::start to get the thread's event loop started.
NOTE 1: I assume you're using a fairly recent version of Qt (>= 4.8).
NOTE 2: If you're using QSqlDatabase and friends to access your DB, make sure to create the DB connection in the worker object after it is moved to the new thread.
I was writing an application in Play 2.3.7 and when trying to create an actor (using the default Akka.system() of Play) inside the beforeStart overriden method of the Global object, the application crashes with some infinite recursive call of beforeStart, ultimately throwing an exception due to Global object not being initialized. If I create this actor inside the onStart method, then everything goes well.
My "intuition" was: "ok, this actor must be ready before the application receives the first request, so it must be created on beforeStart, not in onStart".
When is Akka.system() ready to use?
Akka.system returns an ActorSystem held by the AkkaPlugin. Therefore, if you want to use it, you must do so after the AkkaPlugin has been initialized. The AkkaPlugin is given priority 1000, which means its started after most other internal plugins (database, evolutions, ..). The Global plugin has priority 10000, which means the AkkaPlugin is available there (and for any plugin with priority > 1000).
Note the warning in the docs about beforeStart:
Called before the application starts.
Resources managed by plugins, such as database connections, are likely not available at this point.
You have to start this in onStart() because beforeStart() is called too early - way before anything like Akka (which is actually a plugin) or any database connections are created. In fact, the documentation for GlobalSettings states:
Resources managed by plugins, such as database connections, are likely not available at this point.
The general guidance (confirmed by this thread) is that onStart() is the place to create your actors. And in practice, that has worked for me as well.
I have an out of process ATL COM server (exe). When it is started by a Client the server spawns a worker thread which polls for some data. Every time the data is updated I want to notify all of the clients with the updated value.
I have created a COM Client, which connects via CoCreateInstanceEx, creates its Sink object, gets the connection point and calls Advise, all without error. However, When the server tries to Fire_event, it's IConnectionPointImpl::m_vec is empty and no clients are ever notified.
I assume this is because the server creates its own object, so I end up with two instances of IConnectionPointImpl::m_vec, one from the server and one from the client when it calls Advise. How can I get the server data to the clients?
I'd recommend this approach. Create a plain vanilla C++ singleton (not a COM object) - let's call it S. S would hold a list of weak, non-AddRef'ed references to all outstanding COM objects (a C++ class pointer, rather than a COM interface pointer, would be convenient). Your COM objects would register themselves with S in their constructor, and deregister in destructor.
When something interesting happens, your worker thread would notify (call a method on) S, which would notify all registered COM objects, which would call Fire_event on themselves.
Be careful when firing events from a worker thread. This is illegal, unless both your main thread and worker thread enter MTA. See http://vcfaq.mvps.org/com/1.htm for details and some workarounds.
I'm trying to enable multiple simultaneous client access to a webservice, enabeling a client to make a request and block until data is available (I am doing it this way since gsoap does not support notifications)
My webservice class is compiled with WITH_PURE_VIRTAL, meaning that I can't create instances of it, as it is an abstract class. Thus, I use one class built by me, which inherits from the webservice class, and is responsible for managing the webservice and webclient requests.
However, when my class is busy handling an existent client, I can't seem to receive any other requests.
I read (here) that you should launch a thread with something similar to this:
soap_serve((struct soap*)soap);
soap_destroy((struct soap*)soap); // dealloc C++ data
soap_end((struct soap*)soap); // dealloc data and clean up
soap_done((struct soap*)soap); // detach soap struct
free(soap);
However, when I modify the that code to call my webservice class instead, the serve call doesn't do anything.
I also tried launching a new thread inside my webservice call methods, but as soon as the thread launches, the webclient receives an empty response.
Does anyone have any suggestions?
If you look at my answer to this question you can see a very basic C++ threaded gSoap server. What I think you may be missing is the need to copy the service class, in my code the line tc = c.copy() ; // make a safe copy this copies the gSoap service instance including the gSoap context; it's this copy that's passed into the new thread so that the new thread can respond to the request while the main thread waits for another request to be made.
I am designing a game server with scripting capabilities. The general design goes like this:
Client connects to Server,
Server initializes Client,
Server sends Client to EventManager (separate thread, uses libevent),
EventManager receives receive Event from Client socket,
Client manages what it received via callbacks.
Now the last part is what's the most tricky for me now.
Currently my design allows me for a class which inherits Client to create callbacks to specific received events. These callbacks are managed in a list and the received buffer goes through a parsing process each time something is received. If the buffer is valid, the callback is called where it is act upon what is in the buffer. One thing to note is that the callbacks can go down to the scripting engine, at which point nothing is sure what can happen.
Each time a callback finishes, the current receive buffer has to be reset etc. Callbacks currently have no capability of returning a value, because as stated before, anything can happen.
What happens is that when somewhere in the callback something says this->disconnect(), I want to immediately disconnect the Client, remove it from the EventManager, and lastly remove it from the Server, where it also should get finally destructed and free memory. However, I still have some Code running after the callback finishes in the Client, thus I can't free memory.
What should I change in the design? Should I have some timed event in the Server which checks which Clients are free to destroy? Would that create additional overhead I don't need? Would it still be okay after the callback finishes to run minimal code on the stack (return -1;) or not?
I have no idea what to do, but I am open for complete design revamps.
Thanks in advance.
You can use a reference counted pointer like boost::shared_ptr<> to simplify memory management. If the manager's client list uses shared_ptrs and the code that calls the callbacks creates a local copy of the shared_ptr the callback is called on, the object will stay alive until it is removed from the manager and the callback function is complete:
class EventManager {
std::vector< boost::shared_ptr<Client> > clients;
void handle_event(Event &event) {
// local |handler| pointer keeps object alive until end of function, even
// if it removes itselfe from |clients|
boost::shared_ptr<Client> handler = ...;
handler->process(event);
}
};
class Client {
void process(Event &event) {
manager->disconnect(this);
// the caller still holds a reference, so the object lives on
}
}
The Client object will automatically be deleted once the last shared_ptr to it goes out of scope, but not before. So creating a local copy of the shared_ptr before a function call makes sure the object is not deleted unexpectedly.
You should consider having an object like "Session" which will track particular message flow from start to finish (from 1 client).
This object should also take care of current state: primarily the buffers and processing.
Each event which triggers a callback MUST update the state of corresponding session.
Libevent is capable of providing you with any result of scheduled event: success, failure, timeout. Each of this types should be reflected with your logic.
In general, when working with events, consider your processing logic to be an automaton with a state.
http://en.wikipedia.org/wiki/Reactor_pattern may be a good resource for your task.
Let the Client::disconnect() function send an event to the EventManager (or Server) class. This means that you need some sort of event handling in EventManager (or Server), an event loop for instance.
My general idea is that Client::disconnect() does not disconnect the Client immediately, but only after the callback finished executing. Instead, it just posts an event to the EventManager (or Server) class.
One could argue that the Client::disconnect() method is on the wrong class. Maybe it should be Server::disconnect( Client *c ). That would be more in-line with the idea that the Server 'owns' the Client and it's the Server which disconnects Clients (and then updates some internal bookkeeping).