Re: Two-step object initialization (using a thread)
Hi!
vl106 schrieb:
int main() {
int* val = new int(0);
C aC(val);
thread(val);
aC.f();
return 0;
}
Ok, apart from your problem: replace the heap object with a stack based
object:
int main() {
int val(0);
C aC(&val);
thread(&val);
aC.f();
}
Regarding your problem: you do not ensure the thread runs before the
aC.f() call. The thread might have been created and started, but not yet
scheduled for CPU time. That means you "threadsafe_begin" in C::f will
enter although val is not initialized. Further C::f seems to be the only
consumer of val, thus does not need to be protected. But you need to
ensure the thread runs before you call C::f. Use a condition for this
(conditions are available with pthreads and with boost thread library):
I assume RAII controled mutex, lock and condition objects and class
interface like Boost.
Mutex mutex; //shared mutex object
Condition threadFinished; //shared condition
int main() {
int val(0);
C aC(&val);
{ //local scope
Lock lock(mutex); //lock mutex
thread(&val);
threadFinished.wait(lock); //wait for finish
} //unlock mutex
aC.f();
}
void thread(int* const val)
{
*val = 1234;
Lock lock(mutex); //lock mutex for synchronization
threadFinished.notify_all();
}
void C::f()
{
//do something useful
std::cout << *val;
}
HTH,
Frank
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]