这个错误时是在我测试wxThread功能的时候出现的,之前一直都是在GUI程序中编写,这次由于我需要单独检查wxThread的功能,于是我就写了一个main函数来调用wxThread,编译能够通过,但是运行的时候一直出错,根据debug 我确定是在生成wxThread实例的时候访问了一个未初始化的锁,这个问题困扰了我大概一天时间,我在官网论坛上找到了对应的解决方案,这里分享一下。
出现这个错误的主要原因是在使用wxWidgets内部数据结构的时候没有调用wxInitializer方法,部分的内置变量未初始化
Your lucky day - I got exactly the same error yesterday :wink: You need to call wxInitialize() before doing any wx stuff, and then wxUninitialize before exit. Alternatively, #include "wx/init.h" and use wxInitializer (see the samples/console for how to use it).
phlox: "Hello" is a literal, it exists a bit longer than the program runs. But I'm absolutely certain the example won't compile as it is. The msg member should be at least of type const char*.
出自https://forums.wxwidgets.org/viewtopic.php?t=7195
原来的测试代码
#include "iostream"
#include "wx/wx.h"
#include "wx/thread.h"
using namespace std;
class MyThread : public wxThread
{
public:
MyThread();
virtual ~MyThread();
// thread execution starts here
virtual void *Entry();
};
MyThread::MyThread()
{
cout<<"elle"<<endl;
}
void * MyThread::Entry()
{
// while (!TestDestroy())
int i = 10;
while(i-- >0)
{
// ... do a bit of work...
wxThread::Sleep(100);
cout<< "hello"<<endl;
}
return (wxThread::ExitCode)0; // success
}
MyThread::~MyThread()
{
}
int main()
{
wxThread *p_thread = new MyThread;
if ( <span style="font-family: Arial, Helvetica, sans-serif;">p_thread->Run()</span><span style="font-family: Arial, Helvetica, sans-serif;"> != wxTHREAD_NO_ERROR )</span>
{
wxLogError(wxT("Can't create thread!"));
}
wxThread::Sleep(2000);
return 0;
}
修改之后的代码
#include "iostream"
#include "wx/thread.h"
#include "wx/wx.h"
#include "wx/init.h"
using namespace std;
class MyThread : public wxThread
{
public:
MyThread();
virtual ~MyThread();
// thread execution starts here
virtual void *Entry();
};
MyThread::MyThread()
{
cout<<"elle"<<endl;
}
void * MyThread::Entry()
{
// while (!TestDestroy())
int i = 10;
while(i-- >0)
{
// ... do a bit of work...
wxThread::Sleep(1000);
cout<< "hello"<<endl;
//wxLogMessage("hello");
}
return (wxThread::ExitCode)0; // success
}
MyThread::~MyThread()
{
}
int main()
{
wxInitialize();
wxThread *p_thread = new MyThread;
p_thread->Run();
wxThread::Sleep(15000);
return 0;
}