簡體   English   中英

從另一個線程C / C ++對主線程執行類方法或函數(靜態方法)

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

是否有可能在Windows / UNIX(而非iOS)的C / C ++上創建iOS Objective-c“ performSelectorOnMainThread”功能中的等效功能。 非常感謝。

不,您必須自己動手。 一種實現方法是保留一個全局函數指針,供您的主線程檢查主循環的每次迭代。 例如:

// 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);
}

對於Windows而不是POSIX,請分別使用CRITICAL_SECTIONEnterCriticalSectionLeaveCriticalSection代替pthread_mutex_tpthread_mutex_lockpthread_mutex_unlock ,並且不要忘記適當地初始化和取消初始化關鍵部分。

如果全部在iPhone上,則可以使用CFRunLoopAddSource(),也可以通過具有Objective C ++文件(擴展名為.mm)來在performSelectorOnMainThread上提供C ++友好的包裝。 我建議第二種方式。

如果在其他平台上-請指定平台。 Windows有這樣的方式(APC和消息)。

沒有平台無關的方式,因為沒有諸如平台無關的線程之類的東西。

如果東西必須同時在Unix和Windows上運行(並且您正在使用c ++),請對線程和互斥鎖使用boost

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM