6

私はC++に非常に慣れていません。

クラスがあり、クラスの関数内にスレッドを作成したいと考えています。そして、そのスレッド(関数)は、クラス関数と変数も呼び出してアクセスします。最初は Pthread を使用しようとしましたが、クラスの関数/変数にアクセスしたい場合、範囲外のエラーが発生しました。Boost/thread を調べてみましたが、(他の理由で) ファイルに他のライブラリを追加したくないため、望ましくありません。

私はいくつかの調査を行いましたが、有用な答えが見つかりません。私を導くためにいくつかの例を挙げてください。どうもありがとう!

pthread を使用してみます (ただし、上記の状況に対処する方法がわかりません):

#include <pthread.h>

void* print(void* data)
{
    std::cout << *((std::string*)data) << "\n";
    return NULL; // We could return data here if we wanted to
}

int main()
{
    std::string message = "Hello, pthreads!";
    pthread_t threadHandle;
    pthread_create(&threadHandle, NULL, &print, &message);
    // Wait for the thread to finish, then exit
    pthread_join(threadHandle, NULL);
    return 0;
}
4

2 に答える 2

12

静的メンバー関数を pthread に渡し、オブジェクトのインスタンスをその引数として渡すことができます。イディオムは次のようになります。

class Parallel
{
private:
    pthread_t thread;

    static void * staticEntryPoint(void * c);
    void entryPoint();

public:
    void start();
};

void Parallel::start()
{
    pthread_create(&thread, NULL, Parallel::staticEntryPoint, this);
}

void * Parallel::staticEntryPoint(void * c)
{
    ((Parallel *) c)->entryPoint();
    return NULL;
}

void Parallel::entryPoint()
{
    // thread body
}

これは pthread の例です。おそらく、ほとんど問題なく std::thread を使用するように適応させることができます。

于 2012-11-03T02:46:40.353 に答える
9
#include <thread>
#include <string>
#include <iostream>

class Class
{
public:
    Class(const std::string& s) : m_data(s) { }
    ~Class() { m_thread.join(); }
    void runThread() { m_thread = std::thread(&Class::print, this); }

private:
    std::string m_data;
    std::thread m_thread;
    void print() const { std::cout << m_data << '\n'; }
};

int main()
{
    Class c("Hello, world!");
    c.runThread();
}
于 2015-07-13T11:42:00.970 に答える