2016-07-01 12 views
0

std :: threadメンバ関数。このポインタによってクラスフィールドにアクセスする必要がありますか?以下のようなクラスを考えると

class MyClass { 
    private: 
    vector<std::string> data; 

    void threadWork(std::vector<std::string> *data_ptr) { 
    // some thread work... e.g 
    for(int i=0; i < data_ptr->size(); i++) { 
     std::string next = (*data_ptr)[i]; 
     // do stuff 
    } 
    } 

    void callThreadedFunc(int nthread) { 
    std::vector<std::thread> tgroup; 
    std::vector<std::string> data_ptr = &data; 
    for(int i=0; i < nthreads; i++) { 
    tgroup.push_back(std::thread(&myClass::threadWork, this, data_ptr)); 
    } 
    for(auto &t : tgroup) {t.join();} 
    } 
} 

thisは、スレッドのコンストラクタに渡すことが必要です。これは、フィールド固有のポインタではなく、thisによってスレッドが必要とするすべてのクラスフィールドにアクセスする必要があることを意味しますか? たとえば、次のようにthreadWork()dataにアクセスしてはならない:

void threadWork(MyClass *obj) { 
// some thread work... e.g 
    for(int i=0; i < obj->data.size(); i++) { 
    std::string next = obj.data[i]; 
    // do stuff 
    } 
} 

答えて

3

threadWorkはメンバ関数であり、あなたが適切にthisを使用してスレッドを作成しているので、あなたは通常、インスタンスのすべてのメンバ変数にアクセスすることができ、ポインタを渡す必要がまたはデータへの参照。

だけ

std::thread(&myClass::threadWork, this) 

を行うと、十分です、その後、スレッド関数で使用すると、通常のメンバ変数を使用することができます。

void threadWork(/* no argument */) { 
    // some thread work... e.g 
    for(int i=0; i < data.size(); i++) { 
     std::string next = data[i]; // Uses the member variable "normally" 
     // do stuff 
    } 
} 
+1

しかし、フィールドへのポインタを渡しても有効なのですか?私は実際には2つの異なるベクトルを持ち、重複するコードを減らすために、2つのうちの1つを渡します。 –

+1

@izaak_pyzaakもちろん、スレッド関数に引数として渡すことができますが、メンバ変数に直接アクセスしない場合は、関数を静的にしてからポインタ(または参照)をデータはスレッドを作成するときに 'this'の代わりに機能するはずです。 –

関連する問題