Sunday, April 22, 2012

Thread Safe example -using wxwidgets


#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <wx/thread.h>
#include <wx/log.h>
#include <wx/app.h>

using namespace std;

static wxCriticalSection * critsect = NULL;

class MyThread : public wxThread
{
public:
MyThread(unsigned int& c, wxThreadKind kind = wxTHREAD_JOINABLE);
virtual ~MyThread();

protected:
virtual ExitCode Entry();

private:
unsigned int& counter;
};

MyThread::MyThread(unsigned int& c, wxThreadKind kind) : wxThread(kind), counter(c)
{
}

MyThread::~MyThread()
{
}

wxThread::ExitCode MyThread::Entry()
{
while (counter < 0xFFFFFFFF)
{
critsect->Enter();
++counter;
critsect->Leave();
}

return 0;
}

int main(int argc, char** argv)
{
unsigned int uicounter = 0;

if (argc || argv) argc;

wxInitializer initializer;
if (!initializer)
{
fprintf(stderr, "Failed to initialize the wxWidgets library, aborting.");
return -1;
}

critsect = new wxCriticalSection();
if (critsect == NULL)
{
fprintf(stderr, "Failed to create the critical section object, aborting.");
return -2;
}

MyThread *mt = new MyThread(uicounter);
if (mt)
{
if (mt->MyThread::Create() == wxTHREAD_NO_ERROR)
{
mt->Run();
while (mt->IsRunning() == true)
{
critsect->Enter();
cout << uicounter << endl;
critsect->Leave();

wxThread::Sleep(1000);
}
}
}
mt->Delete();
delete mt;

return 0;
}