【问题标题】:How to create multi tasks each one in a separate thread?如何在单独的线程中创建多个任务?
【发布时间】:2018-05-09 14:15:41
【问题描述】:

我有两个静态方法:

  • bool getPicture(const std::string url, const std::string keywords ="")
  • bool showPicture(wxStaticBitmap *viewer)

这些方法每个都执行单独的任务,因此,我希望每个方法都在单独的线程中执行。

#include <wx/thread.h>

// Declaration

class CThread : public wxThread {
public:
    CThread() = default;
    ~CThread() = default;
    void *Entry();
};

// Implementation

void* CThread::Entry() {
    CPublic::getPicture(mainFrm::getInstance()->targetURL, CPublic::getConfigItem("settings/keywords").ToStdString());
    // CPublic::showPicture(mainFrm::getInstance()->viewer_btmp);
    return 0;
}

// Create an instance

wxThread *th = new CThread();
th->Create();
th->Run();

正如您在前面的代码中看到的,每个线程类中都有一个Entry() 方法,因此,我想要另一个Entry() 方法来将我的下一个方法showPicture() 放入其中。

我是否必须创建另一个具有另一个 Entry() 方法将我的 showPicture() 方法放入其中,以在另一个单独的线程还是有其他方法?

【问题讨论】:

标签: c++ multithreading wxwidgets


【解决方案1】:

快速回答:
一个类的所有实例(wxThread 是一个类)共享它的方法。所以如果你想要一个不同的Entry(),你需要一个新的 wxThread 派生类。

关于多线程的建议:
虽然getPicture() 可以在辅助线程中执行,但showPicture() 应该在主线程中执行,因为它是绘制到窗口中的正确位置。强烈建议所有 GUI 内容在主线程中完成。
一个罕见的期望是在辅助线程中使用 OpenGL,而不是通过操作系统命令进行绘制。

关键是辅助线程向主线程发布一条消息,告诉“我完成了,图像可用”。
新数据(已处理的图像)可以放在主线程(例如,将要绘制它的窗口)可以读取它的位置。
使用wxCriticalSectionLocker 防止任何其他线程在工作线程(用于getPicture())正在写入时访问数据。

更多信息请访问wxWidgets docsmore wxWidgets doc 和 wxWidgets 分发提供的threadsample。

【讨论】:

  • The point is that the secondary thread posts a message to the main thread telling "I'm done, image is available". 。我如何知道线程已完成任务并准备就绪?
  • @LionKing 在辅助线程中,getPicture() 结束后,在退出Entry() 之前发布消息
  • 关于,While getPicture() can be executed in a secondary thread, showPicture() should be executed in the main thread because it's the right place to draw into the window。将showPicture()放在主窗口中,getPicture()放在一个线程中,结果是showPicture()不显示当前图像而是显示previos图像
  • 窗口必须有一个成员函数来处理从辅助线程接收到的消息。使用Bind。在这个函数中,你调用showPicture()
  • Use Bind.,将使用什么类型的事件?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
  • 2012-06-15
  • 1970-01-01
  • 2021-09-03
相关资源
最近更新 更多