Execute class method or function(static method) on main thread from another thread C/C++
Is it possible to create some of equ开发者_JS百科ivalent in iOS objective-c "performSelectorOnMainThread" functionality on C/C++ for Windows and UNIX, not iOS. Many thanks.
No, you'll have to roll your own. One way to do this would be to keep a global function pointer that your main thread checks each iteration of the main loop. For example:
// Global variables
pthread_mutex_t gMutex = PTHREAD_MUTEX_INITIALIZER;
void (*gFuncPtr)(void*);
void *gFuncArg;
// Your program's main loop in the main thread
while(programIsRunning())
{
// If we have a function to call this frame, call it, then do the rest of
// our main loop processing
void (*funcPtr)(void*);
void *funcArg;
pthread_mutex_lock(&gMutex);
funcPtr = gFuncPtr;
funcArg = gFuncArg;
gFuncPtr = NULL;
pthread_mutex_unlock(&gMutex);
if(funcPtr != NULL)
(*funcPtr)(funcArg);
// Rest of main loop
...
}
// Call this function from another thread to have the given function called on
// the main thread. Note that this only lets you call ONE function per main
// loop iteration; it is left as an exercise to the reader to let you call as
// many functions as you want. Hint: use a linked list instead of a single
// (function, argument) pair.
void CallFunctionOnMainThread(void (*funcPtr)(void*), void *funcArg)
{
pthread_mutex_lock(&gMutex);
gFuncPtr = funcPtr;
gFuncArg = funcArg;
pthread_mutex_unlock(&gMutex);
}
For Windows instead of POSIX, use CRITICAL_SECTION
, EnterCriticalSection
, and LeaveCriticalSection
instead of pthread_mutex_t
, pthread_mutex_lock
, and pthread_mutex_unlock
respectively, and don't forget to initialize and deinitialize the critical section appropriately.
If it's all on the iPhone, you can either use CFRunLoopAddSource(), or provide a C++-friendly wrapper over performSelectorOnMainThread by having an Objective C++ file (extension .mm). I recommend the second way.
If it's on a different platform - please specify the platform. Windows has such means (APC and messages).
No platform-indepenent way, since there's no such thing as platform-independent threads.
If the thing has to run on both unix and windows (and you are using c++), use boost for threads & mutexes
精彩评论