2013-06-11 23 views
1

我有一個關於C++ pthread的問題。在pthread中的Obj-C performSelector OnThread C++

如果我有一個Thread1和Thread2。

有沒有辦法在Thread1中調用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的方式。

+0

是您的目標來調用的Objective-C是C++的方法在後臺線程粗的例子嗎? –

+0

您可以將C++方法調用包裝到用* performSelector:onThread:*調用的Objective-C方法中。 –

+0

不,也許......不僅是明確的obj-c沒有被使用。我只使用C + +,我想有類似的東西在obj-c – Safari

回答

1

沒有類似的方法來做到這一點與純pthreads。這個(你所指的objective-C函數)只適用於具有運行循環的線程,所以它僅限於objective-C。

pure-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 
} 
+0

中使用我認爲這是最接近我的問題 的答案,但不是我想要做的 – Safari