user15284017
user15284017

Reputation:

When marshaling a COM interface to multiple threads, is cloning the stream sufficient, or is copying it necessary?

According to Raymond's guide, when marshaling a COM interface to multiple threads, you must "[t]ransmit a copy of the stream to each of the threads you want to share the object with." (Or you could use a mutex, but let's set that option aside for now.)

I was wondering if using IStream::Clone will suffice for that purpose, or whether that doesn't count as a copy.

Also, if IStream::Clone is fine, I was wondering if you need to call it from the thread that created the original stream, or if one of the background threads can call it. I'm wondering whether, if a background thread called it, you'd wind up with the exact situation we're trying to avoid in the first place (sharing COM pointers across threads).

Thank you for any info.

Upvotes: 2

Views: 99

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596497

Yes, without using a synchronizing mutex, you would need to Clone() the original stream for each thread, that way each clone has its own read/write seek position that is independent of the other clones.

The Clone method creates a new stream object with its own seek pointer that references the same bytes as the original stream.

Raymond's guide even eludes to this:

Transmit a copy of the stream to each of the threads you want to share the object with. (You need to use a copy so that the multiple threads don’t all try to use the same stream and step on each other’s stream position. Alternatively, you could be clever and use the same stream, but use a mutex or other synchronization object to make sure only one thread uses the stream at a time.)

Upvotes: 1

Related Questions