Tuesday, March 27, 2012 12:44 PM
I want to use task parallelism from ppl (e.g. task group ).
Inside the task function though I need to initialize COM. The requirement is that COM is initialized from every thread that might be executing my task function.
Is there a way to get the underlying thread id of the currently executing task so that I can initialize COM if not initialized already ? Or is there any other option in this regard ?
Tuesday, March 27, 2012 2:44 PM
It seems to be quite safe to call CoInitialize() multiple times from the same thread as long as you keep that initialization consistent between threads.
I don't have any better idea.
Tuesday, March 27, 2012 5:59 PMOwner
1. id = GetCurrentThreadId() 2. Do a TLS lookup for a flag 3. If a flag is not set then, a.Do COM init b. Set the flag
There isnt a direct friendly way of saying "call CoInitialize" for every thread that is created by ConcRT.
However, you can take advantage of the current implementation details (with caveats of course). Every task is ultimately backed by a thread. And the current runtime design makes it ok to call GetCurrentThreadId().
If you want to avoid calling it multiple times, then you use TLS to initialize a flag per thread. If that flag is not already set then a) call coinitialize b)set the flag
However, the caveat is that there is no clean way to clean up the TLS or COM init upon task completion - So the thread may carry over this state when executing other tasks.
Rahul V. Patil
Tuesday, March 27, 2012 7:18 PM
Thanks for the replay.
So basically I can init COM inside the task work function(bases on a lookup thread id - flag set) but there is no clean way to know when a task is finished that I have to do the reverse CoUninitialize() ? Can't I just call CoUninitialize() before returning from task and at the same time clear the flag from lookup table ? Next time I initialize COM again for the same OS thread...
Tuesday, March 27, 2012 7:44 PMOwner
Yes - that would work. Do double check performance numbers though.
One other way to deal with the clean up is to explicitly create a scheduler and do all the com related work in that scheduler, and then retire the scheduler. That would make sure that those threads dont get reused for other purposes. [Again, this is taking advantage of implementation details - and not specs].
Rahul V. Patil
- Marked As Answer by raiderG Tuesday, March 27, 2012 7:49 PM