There are two solutions. The simplest is often just to allocate
the arguments dynamically: in NewProcess
:
ThrArgs* args = new ThrArgs( entryPoint, processArg, ccpu );
bool results = pthread_create( &thread, NULL, StartWork, args ) == 0;
if (!results) {
delete args;
}
(You could use std::unique_ptr
or std::auto_ptr
here as
well. In which case, don't call release on it unless
pthread_create
succeeds!)
The alternative is to create a conditional variable over
a boolean, then wait on it before leaving the function, and copy
the parameters and then set the boolean in the new thread: in
NewProcess
:
pthread_mutex_lock( &theMutex );
freeToContinue = false;
bool results = pthread_create( &thread, NULL, StartWork, args ) == 0;
if ( results ) {
while ( !freeToContinue ) {
pthread_cond_wait( &theCond, &theMutex );
}
pthread_mutex_unlock( &theMutex );
}
return results;
and in StartWork
(the function you pass to pthread_create
must be extern "C"
, and so cannot be a member):
void* StartWork( void* arguments )
{
pthread_mutex_lock( &theMutex );
ThrArgs args = *static_cast<ThrArgs*>( arguments );
freeToContinue = true;
pthread_cond_broadcast( &theCond );
pthread_mutex_unlock( &theMutex );
// ...
}
(Obviously, I've left out a lot of error checking here.)
Either way: you may have to do something similar with regards to
the processArg
argument, since its lifetime is determined by
that of the caller.
And you don't need all of the casts to void*
.