私はブーストスレッドを使うことを学んでいます。私は両方のスレッドで利用可能なキューに数値を送り、ワーカースレッドに出力するシンプルなプログラムを作ろうとしています。私はそれを1ブーストスレッドが終了するのをメインが待たないようにしますか?
を養う場合、私は参加を呼び出すときに問題があるワーカースレッドがシャットダウンするように
が、私はそれを作った、私のメインスレッドはただそこに座って、終了するワーカースレッドを待ちます。これいらない。私はメインがワーカースレッドと並行して実行し続けるようにしたい。
template<typename Data>
class concurrent_queue
{
private:
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
public:
void push(Data const& data)
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
bool empty() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.empty();
}
bool try_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
if(the_queue.empty())
{
return false;
}
popped_value=the_queue.front();
the_queue.pop();
return true;
}
void wait_and_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
while(the_queue.empty())
{
the_condition_variable.wait(lock);
}
popped_value=the_queue.front();
the_queue.pop();
}
};
void workerFunc(concurrent_queue<int>* q)
{
while(true)
{
while(!q->empty())
{
int p = -1;
q->wait_and_pop(p);
std::cout << p;
if(p == 1)
{
return;
}
}
}
}
int main(int argc, char* argv[])
{
concurrent_queue<int> m_q;
std::cout << "main: startup" << std::endl;
boost::thread workerThread(workerFunc,&m_q);
std::cout << "main: waiting for thread" << std::endl;
m_q.push(6);
m_q.push(11);
workerThread.join();
m_q.push(99); //will not reach here
std::cout << "main: done" << std::endl;
return 0;
}
それはメインスレッドにより、いつでも与えられることができることをいくつかを持っているときおかげ
私はスレッドがアクティブで実行しているだけのプロセス番号になりたいです。
が完了するスレッドオブジェクトの定義が待機により、参加します。メインスレッドを待機させるまで、スレッドに参加しないでください。 – Chad
スレッドをアクティブにして実行し、メインスレッドがいつでも与えることができるスレッド数がある場合にのみ処理します。 – jmasterx
次に私の答えを見てください。 – Chad