简体   繁体   中英

Execute class method or function(static method) on main thread from another thread C/C++

Is it possible to create some of equivalent 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.

如果东西必须同时在Unix和Windows上运行(并且您正在使用c ++),请对线程和互斥锁使用boost

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM