1

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

如果我有一个 Thread1 和 Thread2。

有没有办法在从 Thread1 调用的 Thread2 上执行 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 的方式。

4

1 回答 1

1

纯 pthread 没有类似的方法可以做到这一点。这(您所指的 Objective-C 函数)仅适用于具有运行循环的线程,因此它仅限于 Objective-C。

在纯 c 中没有等效的运行循环/消息泵,这些取决于 guis(例如 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
}
于 2013-06-11T18:20:31.680 回答