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 でこれを行う同様の方法はありません。これ (参照している目的 C 関数) は、実行ループを持つスレッドでのみ機能するため、目的 C に限定されます。

pure-c には実行ループ/メッセージ ポンプに相当するものはありません。これらは GUI (iOS など) に依存します。

唯一の代替手段は、スレッド 2 に何らかの条件をチェックさせ、それが設定されている場合は、事前定義されたタスクを実行することです。(これはグローバル関数ポインターである可能性があり、ポインターが null でない場合、スレッド 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 に答える