views:

108

answers:

4

Googling don't find anything. Are they created at point of use, or are the generic parts shared between instances?

(Same for template classes?)

+10  A: 

Template functions are created at compile time. The template property is completely orthogonal to thread-safety.

Peter G.
That sounds cool, but what does it mean ? :-)
DarkDust
Just in case that wasn't clear enough: C++ Templates are what are referred to as "code generators." By this it means that when the compiler comes across the template, it literally creates a brand new set of machine instructions for each type you use in that template. Because of this, you end up with two completely separate functions that get called. int function<type_a>() is a completely different codepath than int function<type_b>() at the machine level, even though they do the same things. So, their local variables are indeed threadsafe (different stack frames), but not anything else.
Bryan
@Bryan: would different stack frames be created for typedef'd types as well? My knowledge of the compiler-innards is a bit shaky.
slashmais
Typedefs introduce nothing new. They're just aliases to the referenced types.
Peter G.
@slashmais: Think of it this way. The <type> notation to indicate a template is really just a cool compiler trick saying "I want to write 6 functions to handle six types, that all do the same thing"... You get completely different functions. Like Peter pointed out, a typedef is just a way of referencing some other type, so you'll still get a new function specifically for that referenced type.
Bryan
So I understood, thanks. Pity though.
slashmais
+2  A: 

Template functions are simply ...templates used by the compiler to generate "normal" functions. So it's the same as normal functions, there is no difference.

Klaim
+5  A: 

They're no more or less thread-safe than any other type of function.

Michael Burr
+1: In other words, no.
John Dibling
@John Dibling: In another word, *mu*. http://www.catb.org/jargon/html/M/mu.html
Shmoopty
@Shmoopty: much better
John Dibling
+2  A: 

The only way I can think of thread safety being affected by this is that if someMethod<typename T>() wasn't thread safe then it would still be okay for a thread to operate on someMethod<int>() while another worked on someMethod<std:string>(), as long as the lack of thread-safety didn't come from their both calling into some non-templated function.

The situation where something else is guaranteeing that only one thread is doing a particular task with a particular type at a time seems pretty unlikely though.

Jon Hanna