在非GUI程序中调用wxThread出现segmentation fault

这个错误时是在我测试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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值