Obj-C performSelector OnThread in pthread C++

Obj-C performSelector OnThread in pthread C++

本文关键字:pthread C++ in OnThread performSelector Obj-C      更新时间:2023-10-16

我有一个关于c++ pthread的问题。

如果我有一个Thread1和Thread2。

是否有一种方法可以在Thread2上执行从Thread1调用的Thread2方法?

//code example
//we can suppose that Thread2 call has a method 
void myThread2Method();
//I would to call this method from Thread1 but your execution  must to run on Thread2..
thread1.myThread2Method()

我想知道是否存在类似于Obj-c中存在的performSelector OnThread的方式。

对于纯pthread没有类似的方法。这个(你提到的objective-C函数)只适用于有运行循环的线程,所以它仅限于objective-C。

在pure-c中没有等价的运行循环/消息泵,这些依赖于gui(例如iOS等)。

唯一的选择是让线程2检查某种条件,如果设置了,则执行预定义的任务。(这可能是一个全局函数指针,如果指针不为空,线程2会定期检查并执行函数)。

下面是一个粗略的示例,展示了基本的工作原理

void (*theTaskFunc)(void);  // global pointer to a function 
void pthread2()
{
    while (some condition) {
       // performs some work 
       // periodically checks if there is something to do
       if (theTaskFunc!=NULL) {
           theTaskFunc();      // call the function in the pointer
           theTaskFunc= NULL;  // reset the pointer until thread 1 sets it again 
       }
    }
    ...
}
void pthread1() 
{
      // at some point tell thread2 to exec the task.
      theTaskFunc= myThread2Method;  // assign function pointer
}