[OT] Problem with threads and virtual functions

I could understand that problem happening if I was trying to call derived
class virtuals IN THE CONSTRUCTOR - but I’m not. I’m just creating
threads… the pointer is not dereferenced by the thread until long after
the constructor returns. Indeed, the semaphore is there to guarantee that.

Hm. Are virtual tables for stack variables created in stack space? That
could explain it - when the thread gets created, it would get a copy of the
stack with no virtual table in it yet. Except that still wouldn’t explain
why it doesn’t work when I create the threads after the constructor returns…
perhaps it’s a bug in g++. Anyway, I’ve changed it from a virtual function
to a function pointer, that’s working much better.

I’m not amazingly familiare with g++'s optimization levels, but it’s possible that it is cacheing the address of the virtual function ThreadFunc (which, for most intents and purposes, is non-volitile – which is probably a mistake to bring up on a GCC list about virtual functions in general with multi-threading). If your mtclass ctor has not yet finished by the time the function was called the first time into the thread, then this pointer would still be to the mtclass version of ThreadFunc. This could also explain why the function pointer version worked – g++ won’t cache this (as it is inherantly volitile).

My suggestion, which may or may not work (never tried it), would be to create a boolean flag variable inside the base class, set to false in your mtclass ctor, before you create any threads. At the top of threadroot() make it wait until the flag is set true. Then, in your derived classes, make your ctor set the flag to true (as you’re ensured that the virtual table is updated to the actual class by here).

BTW, vtables are implimented as pointers. Ever class that has virtual functions has a set piece of memory for it’s vtable – and every time a class-type changes (only happens durring ctor’ing through the base list), a single pointer in it changes to point at the vtable for that class. Really shouldn’t have an effect on your code, though.

  • Silicon
    // trying not to claim that he knows that he’s talking about—
    Outgoing mail is certified Virus Free.
    Checked by AVG anti-virus system (http://www.grisoft.com).
    Version: 6.0.536 / Virus Database: 331 - Release Date: 11/3/2003