17

ポインタを引数として取る関数とメインを持つプログラムがあります。main はn 個のスレッドを作成し、それぞれが渡された に応じて異なるメモリ領域で関数を実行しますarg。次にスレッドが結合され、メインは領域間でデータ混合を実行し、古いスレッドと同じ操作を行うn 個の新しいスレッドを作成します。

プログラムを改善するために、スレッドの作成に必要な長い時間を取り除き、スレッドを存続させたいと考えています。スレッドは、メインが動作しているときにスリープし、再び起動する必要があるときに通知する必要があります。同じように、join の場合と同様に、スレッドが機能している場合、メインは待機する必要があります。

私はこれを強力に実装することはできず、常にデッドロックに陥っています。

シンプルなベースライン コードです。これを変更する方法についてのヒントをいただければ幸いです。

#include <thread>
#include <climits>

...

void myfunc(void * p) {
  do_something(p);
}

int main(){
  void * myp[n_threads] {a_location, another_location,...};
  std::thread mythread[n_threads];
  for (unsigned long int j=0; j < ULONG_MAX; j++) {
    for (unsigned int i=0; i < n_threads; i++) {
      mythread[i] = std::thread(myfunc, myp[i]);
    }
    for (unsigned int i=0; i < n_threads; i++) {
      mythread[i].join();
    }
    mix_data(myp); 
  }
  return 0;
}
4

4 に答える 4

20

これは、C++11 標準ライブラリのクラスのみを使用する可能なアプローチです。基本的に、作成する各スレッドには、関連するコマンド キュー (オブジェクトにカプセル化されてstd::packaged_task<>いる) があり、これを継続的にチェックします。キューが空の場合、スレッドは条件変数 ( std::condition_variable) を待機します。

std::mutexおよびRAII ラッパーを使用することでデータ競合が回避されますが、メイン スレッドは、サブミットされた各オブジェクトに関連付けられたオブジェクトを格納してそれを呼び出すstd::unique_lock<>ことにより、特定のジョブが終了するのを待つことができます。std::future<>std::packaged_tast<>wait()

以下は、この設計に従った簡単なプログラムです。コメントは、それが何をするかを説明するのに十分であるべきです:

#include <thread>
#include <iostream>
#include <sstream>
#include <future>
#include <queue>
#include <condition_variable>
#include <mutex>

// Convenience type definition
using job = std::packaged_task<void()>;

// Some data associated to each thread.
struct thread_data
{
    int id; // Could use thread::id, but this is filled before the thread is started
    std::thread t; // The thread object
    std::queue<job> jobs; // The job queue
    std::condition_variable cv; // The condition variable to wait for threads
    std::mutex m; // Mutex used for avoiding data races
    bool stop = false; // When set, this flag tells the thread that it should exit
};

// The thread function executed by each thread
void thread_func(thread_data* pData)
{
    std::unique_lock<std::mutex> l(pData->m, std::defer_lock);
    while (true)
    {
        l.lock();

        // Wait until the queue won't be empty or stop is signaled
        pData->cv.wait(l, [pData] () {
            return (pData->stop || !pData->jobs.empty()); 
            });

        // Stop was signaled, let's exit the thread
        if (pData->stop) { return; }

        // Pop one task from the queue...
        job j = std::move(pData->jobs.front());
        pData->jobs.pop();

        l.unlock();

        // Execute the task!
        j();
    }
}

// Function that creates a simple task
job create_task(int id, int jobNumber)
{
    job j([id, jobNumber] ()
    {
        std::stringstream s;
        s << "Hello " << id << "." << jobNumber << std::endl;
        std::cout << s.str();
    });

    return j;
}

int main()
{
    const int numThreads = 4;
    const int numJobsPerThread = 10;
    std::vector<std::future<void>> futures;

    // Create all the threads (will be waiting for jobs)
    thread_data threads[numThreads];
    int tdi = 0;
    for (auto& td : threads)
    {
        td.id = tdi++;
        td.t = std::thread(thread_func, &td);
    }

    //=================================================
    // Start assigning jobs to each thread...

    for (auto& td : threads)
    {
        for (int i = 0; i < numJobsPerThread; i++)
        {
            job j = create_task(td.id, i);
            futures.push_back(j.get_future());

            std::unique_lock<std::mutex> l(td.m);
            td.jobs.push(std::move(j));
        }

        // Notify the thread that there is work do to...
        td.cv.notify_one();
    }

    // Wait for all the tasks to be completed...
    for (auto& f : futures) { f.wait(); }
    futures.clear();


    //=================================================
    // Here the main thread does something...

    std::cin.get();

    // ...done!
    //=================================================


    //=================================================
    // Posts some new tasks...

    for (auto& td : threads)
    {
        for (int i = 0; i < numJobsPerThread; i++)
        {
            job j = create_task(td.id, i);
            futures.push_back(j.get_future());

            std::unique_lock<std::mutex> l(td.m);
            td.jobs.push(std::move(j));
        }

        // Notify the thread that there is work do to...
        td.cv.notify_one();
    }

    // Wait for all the tasks to be completed...
    for (auto& f : futures) { f.wait(); }
    futures.clear();

    // Send stop signal to all threads and join them...
    for (auto& td : threads)
    {
        std::unique_lock<std::mutex> l(td.m);
        td.stop = true;
        td.cv.notify_one();
    }

    // Join all the threads
    for (auto& td : threads) { td.t.join(); }
}
于 2013-03-06T20:12:36.893 に答える
11

必要な概念はスレッドプールです。このSOの質問は、既存の実装を扱います。

アイデアは、多数のスレッドインスタンス用のコンテナを持つことです。各インスタンスは、タスクキューをポーリングする関数に関連付けられており、タスクが使用可能になると、タスクをプルして実行します。タスクが終了すると(終了した場合でも、それは別の問題です)、スレッドは単にタスクキューにループオーバーします。

したがって、同期キュー、キューのループを実装するスレッドクラス、タスクオブジェクトのインターフェイス、およびすべてを駆動するクラス(プールクラス)が必要です。

または、実行する必要のあるタスク用に非常に特殊なスレッドクラスを作成することもできます(たとえば、パラメーターとしてメモリ領域のみを使用します)。これには、スレッドが現在の反復で完了したことを示す通知メカニズムが必要です。

スレッドのメイン関数はその特定のタスクのループであり、1回の反復の終わりに、スレッドはその終了を通知し、条件変数を待って次のループを開始します。本質的には、スレッド内でタスクコードをインライン化し、キューの必要性を完全になくします。

 using namespace std;

 // semaphore class based on C++11 features
 class semaphore {
     private:
         mutex mMutex;
         condition_variable v;
         int mV;
     public:
         semaphore(int v): mV(v){}
         void signal(int count=1){
             unique_lock lock(mMutex);
             mV+=count;
             if (mV > 0) mCond.notify_all();
         }
         void wait(int count = 1){
             unique_lock lock(mMutex);
             mV-= count;
             while (mV < 0)
                 mCond.wait(lock);
         }
 };

template <typename Task>
class TaskThread {
     thread mThread;
     Task *mTask;
     semaphore *mSemStarting, *mSemFinished;
     volatile bool mRunning;
    public:
    TaskThread(Task *task, semaphore *start, semaphore *finish): 
         mTask(task), mRunning(true), 
         mSemStart(start), mSemFinished(finish),
        mThread(&TaskThread<Task>::psrun){}
    ~TaskThread(){ mThread.join(); }

    void run(){
        do {
             (*mTask)();
             mSemFinished->signal();
             mSemStart->wait();
        } while (mRunning);
    }

   void finish() { // end the thread after the current loop
         mRunning = false;
   }
private:
    static void psrun(TaskThread<Task> *self){ self->run();}
 };

 classcMyTask {
     public:
     MyTask(){}
    void operator()(){
        // some code here
     }
 };

int main(){
    MyTask task1;
    MyTask task2;
    semaphore start(2), finished(0);
    TaskThread<MyTask> t1(&task1, &start, &finished);
    TaskThread<MyTask> t2(&task2, &start, &finished);
    for (int i = 0; i < 10; i++){
         finished.wait(2);
         start.signal(2);
    }
    t1.finish();
    t2.finish();
}

上記で提案された(粗い)実装は、Task提供しなければならないタイプoperator()(つまり、クラスのようなファンクター)に依存しています。先ほどスレッド関数本体に直接タスクコードを組み込むことができると言ったのですが、わからないのでできるだけ抽象化していきました。スレッドの開始用と終了用の条件変数が1つあり、どちらもセマフォインスタンスにカプセル化されています。

の使用を提案している他の答えを見て boost::barrier、私はこのアイデアをサポートすることしかできません:可能であれば、セマフォクラスをそのクラスに置き換えるようにしてください。その理由は、自己実装ではなく、十分にテストされ維持されている外部コードに依存する方が良いからです。同じ機能セットのソリューション。

全体として、どちらのアプローチも有効ですが、前者は柔軟性を優先してわずかなパフォーマンスを放棄します。実行するタスクに十分な時間がかかる場合、管理とキューの同期のコストはごくわずかになります。

更新:コードが修正され、テストされました。単純な条件変数をセマフォに置き換えました。

于 2013-03-06T16:35:17.863 に答える
5

これは、バリア (条件変数とカウンターに対する便利なラッパー) を使用して簡単に実現できます。基本的に、すべての N スレッドが「バリア」に到達するまでブロックします。その後、再び「リサイクル」されます。Boost は実装を提供します。

void myfunc(void * p, boost::barrier& start_barrier, boost::barrier& end_barrier) {
  while (!stop_condition) // You'll need to tell them to stop somehow
  {
      start_barrier.wait ();
      do_something(p);
      end_barrier.wait ();
  }
}

int main(){
  void * myp[n_threads] {a_location, another_location,...};

  boost::barrier start_barrier (n_threads + 1); // child threads + main thread
  boost::barrier end_barrier (n_threads + 1); // child threads + main thread

  std::thread mythread[n_threads];

    for (unsigned int i=0; i < n_threads; i++) {
      mythread[i] = std::thread(myfunc, myp[i], start_barrier, end_barrier);
    }

  start_barrier.wait (); // first unblock the threads

  for (unsigned long int j=0; j < ULONG_MAX; j++) {
    end_barrier.wait (); // mix_data must not execute before the threads are done
    mix_data(myp); 
    start_barrier.wait (); // threads must not start new iteration before mix_data is done
  }
  return 0;
}
于 2013-03-06T17:03:02.827 に答える
0

以下は、いくつかのランダムな処理を実行する単純なコンパイルおよび作業コードです。aleguna のバリアの概念を実装します。各スレッドのタスクの長さは異なるため、強力な同期メカニズムが必要です。同じタスクでプールを行い、結果をベンチマークしてから、Andy Prowl が指摘した先物を使用する可能性があります。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <complex>
#include <random>

const unsigned int n_threads=4; //varying this will not (almost) change the total amount of work
const unsigned int task_length=30000/n_threads;
const float task_length_variation=task_length/n_threads;
unsigned int rep=1000; //repetitions of tasks

class t_chronometer{
 private: 
  std::chrono::steady_clock::time_point _t;

 public:
  t_chronometer(): _t(std::chrono::steady_clock::now()) {;}
  void reset() {_t = std::chrono::steady_clock::now();}
  double get_now() {return std::chrono::duration_cast<std::chrono::duration<double>>(std::chrono::steady_clock::now() - _t).count();}
  double get_now_ms() {return 
      std::chrono::duration_cast<std::chrono::duration<double,std::milli>>(std::chrono::steady_clock::now() - _t).count();}
};

class t_barrier {
 private:
   std::mutex m_mutex;
   std::condition_variable m_cond;
   unsigned int m_threshold;
   unsigned int m_count;
   unsigned int m_generation;

 public:
   t_barrier(unsigned int count):
    m_threshold(count),
    m_count(count),
    m_generation(0) {
   }

   bool wait() {
      std::unique_lock<std::mutex> lock(m_mutex);
      unsigned int gen = m_generation;

      if (--m_count == 0)
      {
          m_generation++;
          m_count = m_threshold;
          m_cond.notify_all();
          return true;
      }

      while (gen == m_generation)
          m_cond.wait(lock);
      return false;
   }
};


using namespace std;

void do_something(complex<double> * c, unsigned int max) {
  complex<double> a(1.,0.);
  complex<double> b(1.,0.);
  for (unsigned int i = 0; i<max; i++) {
    a *= polar(1.,2.*M_PI*i/max);
    b *= polar(1.,4.*M_PI*i/max);
    *(c)+=a+b;
  }
}

bool done=false;
void task(complex<double> * c, unsigned int max, t_barrier* start_barrier, t_barrier* end_barrier) {
  while (!done) {
    start_barrier->wait ();
    do_something(c,max);
    end_barrier->wait ();
  }
  cout << "task finished" << endl;
}

int main() {
  t_chronometer t;

  std::default_random_engine gen;
  std::normal_distribution<double> dis(.0,1000.0);

  complex<double> cpx[n_threads];
  for (unsigned int i=0; i < n_threads; i++) {
    cpx[i] = complex<double>(dis(gen), dis(gen));
  }

  t_barrier start_barrier (n_threads + 1); // child threads + main thread
  t_barrier end_barrier (n_threads + 1); // child threads + main thread

  std::thread mythread[n_threads];
  unsigned long int sum=0;
  for (unsigned int i=0; i < n_threads; i++) {
    unsigned int max = task_length +  i * task_length_variation;
    cout << i+1 << "th task length: " << max << endl;
    mythread[i] = std::thread(task, &cpx[i], max, &start_barrier, &end_barrier);
    sum+=max;
  }
  cout << "total task length " << sum << endl;

  complex<double> c(0,0);
  for (unsigned long int j=1; j < rep+1; j++) {
    start_barrier.wait (); //give to the threads the missing call to start
    if (j==rep) done=true;
    end_barrier.wait (); //wait for the call from each tread
    if (j%100==0) cout << "cycle: " << j << endl;
    for (unsigned int i=0; i<n_threads; i++) {
      c+=cpx[i];
    }
  }
  for (unsigned int i=0; i < n_threads; i++) {
    mythread[i].join();
  }
  cout << "result: " << c << " it took: " << t.get_now() << " s." << endl;
  return 0;
}
于 2013-03-08T15:27:15.383 に答える