私は並列に動作する別のオブジェクトを作成するクラスを設計しています。この並列オブジェクトはGMainLoop
を実行し、さまざまなイベント(この場合はDBus)を待ち受けます。私の問題は、GMainLoop
で実行中のスレッドと通信する方法がわかりません。私はそのスレッドとの通信の方法をGLib
に強制しますか?うまくいけば、私は結局、GLib
への私の依存を取り除くことができるように、標準ライブラリに頼っています。ここに私が達成しようとしているもののおもちゃの例があります:C++ 14とGLib(GDBus)を使用したスレッド通信
// Example program
#include <iostream>
#include <thread>
#include <memory>
#include <glib.h>
class ParallelTask
{
public:
ParallelTask() {
std::cout << "I am alive!\n";
// initialize _mainLoop (allocate, add signals, set priority, etc)
// ...
g_main_loop_run(_mainLoop);
};
~ParallelTask() {
std::cout << "I am dead!\n";
// Misc cleanup
// ...
g_main_loop_quit(_mainLoop);
}
private:
GMainLoop* _mainLoop;
};
class TaskManager
{
public:
TaskManager() = default;
~TaskManager() {join();}
void startTask() {
_thread = std::thread([this](){_task = std::make_unique<ParallelTask>();});
}
void stopTask() {
//??? Need to send message to Parallel task telling it to shut down
join();
}
private:
void join() {
if (_thread.joinable()) {
_thread.join();
}
};
std::thread _thread;
std::unique_ptr<ParallelTask> _task;
};
int main()
{
TaskManager taskManager;
taskManager.startTask();
// Do other stuff
taskManager.stopTask();
}
また、私はLinuxベースのOSで動作しています。私はさらにGLib
よりもpthread
ベースのソリューションを好むだろう。しかし、他に解決策がない場合は、喜んでGLib
提案を受け取ります。ありがとう!
:
g_main_context_iteration
を使用する方法の例。 –