I have a thread that calls various APIs of a COM interface. Now I want to invoke these functions from another thread. Can you please advise how I can achieve this?
How can I implement the communication between these two threads? If I define a Message queue sort of data structure which is common for these two threads then how do I define a common data structure as the parameters are different for each COM API.
Thanks in advance
The typical way is to use callbacks. You pass your data round via pointer. You can either use polymorphism to override the method that the base class calls when you pop it off the queue. Base calls function x, you override function x in derivative classes to achieve what you want.
Another way is to use plain old callbacks. You pass the address of your function onto a queue along with any data you need, wrapped up cleanly in a struct. All of the callbacks must have the same signature, so you'll probably need to cast your data to void.
You don't define one common data structure. There is a different data structure for each different function signature. Only common thing between those structures is identifier of the function. In your thread you'll have giant switch (or std::map) that would translate function identifier to function itself. After that you know how to interpret the rest of the structure. The structures should have POD semantic.
If each thread is running as a single-threaded apartment then you can make calls on the required APIs from a remote thread by marshalling its interface pointer as an IStream from the object's owning thread to the other thread via CoMarshalInterThreadInterfaceInStream and CoGetInterfaceAndReleaseStream. Once the remote thread has an interface pointer, you can make calls on it directly.
You might also be able to do this more simply using the Global Interface Table, depending on your app's threading model. This would be the easiest way.
Related
I'm using the standard C/C++ socket function, but I'd like to encapsulate them into a C++ class. The problem is that the functions for sending and receive returns (or require) pointers to void. Is there any way to use an object that encapsulates those values?
For example, in Java the Socket class uses both ObjectOutputStream and ObjectInputStream in order to work with Object type so every object can be sent via Sockets.
I know that in Java the approach is quite different because the pointers are hidden to the programmer, but is there any similar solution in C++?
socket isn't a c++ function. It's a system level function and it doesn't know anything about objects (or indeed anything in c++), so you have to arrange to provide it with a pointer to the data you want transferred.
As #GCT says, socket isn't a function but is a system level function which is used to handle network connections. In C/C++ each socket is identified with an Integer value, so it's not easy, as you want, to handle it as an object.
I recommend you to read this tutorial to know more about socket.
Maybe it can help you: I have a project that show how to use sockets in C++. Server and client are contained in their own class. You can get it by this link.
TL;DR
Say I implement a class that implements an API that returns a HANDLE.
Say my class is the owner of the HANDLE and responsible to create it, update it and close it.
How do I prevent callers of my API to close my handle and break my design?
BACKGROUND
CreateToolhelp32Snapshot is an expensive call and must be used intelligently.
I have many projects in my solution and each of them calls CreateToolhelp32Snapshot carelessly.
I want to implement an wrapper class that provides "smart" access to CreateToolhelp32Snapshot.
My class will be the owner of the HADNLE returned by CreateToolhelp32Snapshot and will update it (re-call CreateToolhelp32Snapshot) when needed (not yet fully define when it is needed).
For sake of simplicity let's assume my application is a single process & thread and my class has one instance only.
Say I implement a class that implements an API that returns a HANDLE
You broke your design by returning the handle. The users of your wrapper should not care for the handle but for the data that they want like the module list in your case. Expose an API that can return such data to your users.
class snapshot
{
public:
snapshot()
{
m_handle = CreateToolhelp32Snapshot(...);
}
~snapshot()
{
CloseHandle(m_handle);
}
getModules()
{
// use m_handle to return a list of modules.
}
private:
HANDLE m_handle;
};
What you can do is use DuplicateHandle and require that the caller call CloseHandle. Other than that you must trust the caller.
You can't. So long as you are unwilling to fully encapsulate all uses of the HANDLE, external code which can access the HANDLE directly can close it. This is no different from being able to do delete smart_ptr.get();.
C++ can protect you from accidental misuse. It cannot protect you from perfidy. If a user who is using a smart-handle class didn't get the memo that the smart-handle class is the owner of the HANDLE, there's not much you can do.
If I were to implement that class, I would simply write the method Enumerate and would call CreateToolhelp32Snapshot, another set of functions and then CloseHandle. The HANDLE won't be part of the class itself, but local to the Enumerate method.
The enumeration would fill a required struct (user-defined) and would create a vector of that struct (or (unordered_)map, if some PID -> ProcessInformation access is required.).
The class would facilitate methods to get that enumerated data. For a first-class C++ class, I would actually implement begin and end methods so that class/object can be used with range-based for loop.
Why do you really need to delay in the actual processing of CreateToolhelp32Snapshot? By the time a genuine caller calls some safe Win32 API on that handle, the state of running processes would have changed. If the object of your class stays for long(er) then all you've is stale/inconsistent information against that handle.
This is triggered by another question.
Specifically, I have a in process COM class, that is defined in the CLSID registry as having a ThreadingModel of Both.
Our process activates this object through CoCreateInstance (not CoCreateInstanceEx, if that even matters for an in-proc dll server)
Given a threading model of Bothand given th rules listed in the docs:
Threading model of server | Apartment server is run in
------------------------------------------------------
Both | Same apartment as client
and given what Hans writes in the other answer:
... Marshaling occurs when the client call needs to be made on a
different thread. ... can happen when the ThreadingModel specified in
the comClass element demands it. In other words, when the COM object
was created on one thread but is called on another and the server is
not thread-safe.
my tentative conclusion would be that such an object will never need implicit marshalling of calls to its interfaces, since the object will always live in the same apartment as its client.
Is that correct, even if the client process is running as STA?
Yes, there may be marshaling.
If the client of your COM class is running in an STA and you attempt to invoke your class from another apartment, it will have to marshal to the apartment that it was created in.
The COM terminology can be really confusing. When you refer to a 'client' in this case, you're really referring to a thread, not the entire application (as it would imply).
Both just means that the threading model of the server conforms to the client that instantiates it. That is, when you instantiate your class, it takes on the threading model of the thread it was created on. Since you're instantiating the server in an STA, your server will use STA, meaning it can only be invoked on the thread that created it; if another thread tries to invoke it, it will marshal to the thread it was created on.
I can't help myself posting this, although it is not a direct answer to the question.
There's a brilliant MSKB article from the golden ages of COM: INFO: Descriptions and Workings of OLE Threading Models. Still there, and has all the relevant info. The point is, you should not worry about whether there is marshaling or not, if you follow the rules. Just register your object as ThreadingModel=Both, aggregate the Free-Threaded Marshaler with CoCreateFreeThreadedMarshaler, and be done. COM will do the marshaling if needed, in the best possible way. Depending on the client's apartment model, the client code may receive the direct pointer to your interface, if it follows the rules too.
Any "alien" interface that you may receive when a method of your interface gets called, will be valid in the scope of the call, because you stay on the same thread. If you don't need to store it, that's all that matters.
If however you do need to cache the "alien" interface, the right way of doing this would be to store it using CoMarshalInterThreadInterfaceInStream/CoGetInterfaceAndReleaseStream:
To store it:
Enter critical section;
call CoMarshalInterThreadInterfaceInStream and store the IStream pointer in a member field;
Leave critical section;
To retrieve it
Enter critical section;
call CoGetInterfaceAndReleaseStream to retrieve the interface
call CoMarshalInterThreadInterfaceInStream and store it again as IStream for any future use
Leave critical section;
Use the interface in the scope of the current call
To release it:
When you no longer need keeping it, just release the stored IStream (inside the critical section).
If the "alien" object is free-threaded too, and the things are happening inside the same process, you will likely be dealing with a direct interface pointer after CoGetInterfaceAndReleaseStream. However, you should not make any assumptions, and you really don't need to know if the object your dealing with is the original object or a COM marshaller proxy.
This can be slightly optimized by using CoMarshalInterface w/ MSHLFLAGS_TABLESTRONG / CoUnmarshalInterface / IStream::Seek(0, 0) / CoReleaseMarshalData instead of CoGetInterfaceAndReleaseStream/CoGetInterfaceAndReleaseStream, to unmarshal the same interface as many times as needed without releasing the stream.
More complex (and possibly more efficient) caching scenarios are possible, involving Thread Local Storage. However, I believe that would be an overkill. I did not do any timing, but I think the overhead of CoMarshalInterThreadInterfaceInStream/CoGetInterfaceAndReleaseStreamis really low.
That said, if you need to maintain a state that stores any resources or objects which may require thread affinity, other than aforementioned COM interfaces, you should not mark your object as ThreadingModel=Both or aggregate the FTM.
Yes, marshalling is still possible. A couple of examples:
the object is instantiated from an MTA thread and so placed into an MTA apartment and then its pointer is passed into any STA thread and that STA thread calls methods of the object. In this case an STA thread can only access the object via marshalling.
the object is instantiated from an STA thread and so placed into an STA apartment belonging to that thread and then its pointer is passed into another STA thread or an MTA thread. In both cases those threads can only access the object via marshalling.
In fact you can expect no marshalling only in the following two cases:
the object is instantiated from an MTA thread and then only accessed by MTA threads - both the one that instantiated the object and all other MTA threads of the same process.
the object is instantiated from an STA thread and then only accessed by that very thread
and in all other cases marshalling will kick in.
ThreadingModel = Both simply means that the COM server author can give a guarantee that his code is thread-safe but cannot give the same guarantee that other code he didn't write will be called in a thread-safe way. The most common case of getting such foreign code to execute is through callbacks, connection points being the most common example (usually called "events" in client runtimes).
So if the server instance was created in an STA then the client programmer is going to expect the events to run on that same thread. Even if a server method that fires such an event was called from another thread. That requires that call to be marshaled.
I have a C++ multi-threaded application which run tasks in separate threads. Each task have an object which handles and stores it's output. Each task create different business logic objects and probably another threads or threadpools.
What I want to do is somehow provide an easy way for any of business logic objects which are run by task to access each task's output without manually passing "output" object to each business logic object.
What i see is to create output singleton factory and store task_id in TLS. But the problem is when business logic create a new thread or thread pool and those thread would not have task_id in TLS. In this way i would need to have an access to parent's thread TLS.
The other way is to simply grab all output since task's start. There would be output from different task in that time, but at least, better than nothing...
I'm looking for any suggestions or ideas of clean and pretty way of solving my problem. Thanks.
upd: yeah, it is not singletone, I agree. I just want to be able to access this object like this:
output << "message";
And that's it. No worry of passing pointers to output object between business logic classes. I need to have a global output object per task.
From an application point of view, they are not singletons, so why treating the objects like singletons?
I would make a new instance of the output storer and pass the (smart?) pointer to the new thread. The main function may put the pointer in the TLS, thus making the instance global per thread (I don't think that this is a wise design deision, but it is asked). When making a new (sub-?)thread, the pointer can again be passed. So according to me, no singletons or factories are needed.
If I understand you correctly, you want to have multiple class instances (each not necessarily the same class) all be able to access a common data pool that needs to be thread safe. I can think of a few ways to do this. The first idea is to have this data pool in a class that each of the other classes contain. This data pool will actually store it's data in a static member, so that way there is only one instance of the data even though there will be more than one instance of the data pool class. The class will then have accessor methods which access this static data pool (so that it is transparent). To make it thread safe you would then require the access to go through a mutex or something like that.
I rewriting some code that i written a long time ago.
The code is a class that start another worker thread with AfxBeginThread. When the thread ends, it needs to return it work to the calling class.
Actually when the thread ends it send a message by PostMessage with its results to the called class.
But this way is really dependent of MFC, and to do this my class have to implement all the MFC stuffs.
May be correct if instead of send a message it directly call a non-static method of this class ?
Rather than trying to call a method directly (which will introduce a whole new set of threading problems of its own), try using the native Win32 ::PostMessage() instead of the MFC implementation of the same function. Any thread can call ::PostMessage() to deliver a message to another thread safely.
It sounds as though you want to use regular threading primitives, not window messaging primitives.
Which version of AfxBeginThread are you using? If you pass it a class instance, you should be able to access the members of that class directly once you know its finished running. If you passed it a function pointer, you can pass any class pointer in with the lParam parameter, then use that as a communication context.
You just want to make sure that when you access the class you do it in a thread safe manner. If you wait till the thread has ended you should be fine. Otherwise you could use Critical Sections or Mutexes. See the MSDN article on thread synchronization primitives for more info.