WxWidgets 线程在运行期间随机崩溃
我正在编写一个 wxwidget 多线程应用程序。但代码随机崩溃,我对此一无所知。我已经在这里发布了我的代码。每次按下按钮时,该程序都会创建一个线程。这个线程的目的是在父文本区域写一些东西。当我运行代码时,仅打印析构函数消息,即不执行 Entry 部分。我已经为这个问题苦苦挣扎了很长时间。任何帮助将不胜感激。
提前谢谢你..
void threadFrame::addthread(wxCommandEvent &event)
{
mythread *th = new mythread(this);
th->Create();
th->Run();
}
mythread::mythread(GUIFrame *frame) : wxThread(wxTHREAD_DETACHED)
{
m_frame = frame;
}
;
mythread::~mythread()
{
WriteText(wxT("destructor"));
}
void mythread::WriteText(const wxString& text)
{
m_frame->m_textCtrl1->SetValue(text);
}
void *mythread::Entry()
{
WriteText(wxT("thread started"));
return NULL;
}
I'm writing a wxwidget multi-threaded application. But the code crashes randomly of which I have no clue. I've posted my code here. This program creates a thread each time a button is pressed. And this thread is intended to write something on the parent text area. When I run the code, only the destructor message gets printed, ie the Entry section is not executed. I've been struggling with this problem for a lot of time. Any help would be greatly appreciated.
Thanking you in advance..
void threadFrame::addthread(wxCommandEvent &event)
{
mythread *th = new mythread(this);
th->Create();
th->Run();
}
mythread::mythread(GUIFrame *frame) : wxThread(wxTHREAD_DETACHED)
{
m_frame = frame;
}
;
mythread::~mythread()
{
WriteText(wxT("destructor"));
}
void mythread::WriteText(const wxString& text)
{
m_frame->m_textCtrl1->SetValue(text);
}
void *mythread::Entry()
{
WriteText(wxT("thread started"));
return NULL;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该在主线程以外的线程中使用任何 GUI 例程。
这意味着您应该用其他机制替换
->SetValue(..)
调用(例如通过事件通知主线程)。我从未尝试过这样做,所以我不知道这是否会导致线程崩溃。
您是否调用了任何不适合分离线程的函数?
You should not use any GUI-routines from threads other than the main thread.
This means you should replace the
->SetValue(..)
call by some other mechanism (e.g. notify the main thread via event).I never tried to do that, so I don't know if this can cause the thread to crash.
Do you call any functions which are not appropriate for detached threads?
如果您使用 Mutex 函数:wxMutexGuiEnter() 和 wxMutexGuiLeave(),则可以从其他线程访问 GUI。
您确定 GUIFrame 和 threadFrame 可以隐式转换为每个对象吗?你调用 mythread(threadFrame);
您确定您的 Entry() 函数已在 mythread 类中声明吗?
最后,我按照我的“.h”文件声明entry()函数:virtual void * Entry();
You can access the GUI from from other threads provided that you use Mutex functions : wxMutexGuiEnter () and wxMutexGuiLeave () .
Are you sure GUIFrame and threadFrame can cast into each over implicitly? You call mythread(threadFrame);
Are you sure your Entry() function is declared in your mythread class?
Finally, I declare the entry() function as follow my ".h" file : virtual void * Entry();