So I am pretty new to threading in general and have been experimenting with pthreads for the past couple of weeks. I have created a class that has a threaded function within itself. It works fine, until I tried to set a class property (an integer) to a value.
.h file:
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include <iostream>
#include <windows.h>
using namespace std;
class testClass
{
public:
testClass();
HANDLE h;
static DWORD WINAPI mythread(LPVOID param);
int mytestint;
void printstuffs();
void startThread();
};
#endif // TESTCLASS_H
.cpp file
#include "testClass.h"
testClass::testClass()
{
cout << "Created class" << endl;
}
DWORD WINAPI testClass::mythread(LPVOID param)
{
cout << "In thread" << endl;
testClass* This = (testClass*)param;
cout << "Calling class function" << endl;
This->printstuffs();
cout << "Thread is done" << endl;
return NULL;
}
void testClass::printstuffs()
{
cout << "In class function " << endl;
mytestint = 42; // <- crashes here
cout << "Test Int = " << mytestint << endl;
}
void testClass::startThread()
{
h = CreateThread(NULL, 0, mythread, (LPVOID)0, 0, NULL);
cout << "Thread started" << endl;
}
So why does it crash when I call mytestint = 42; ?
You’re calling
mythreadwith a null pointer. When you cast that toThis, you end up calling a function on a null object. When you domytestint = 42, the computer sees it likethis->mytestint = 42, and sincethisisNULL, you dereference a null pointer, and the program segfaults. You need to do something like the following:If possible, I would also suggest migrating over to standard C++ threads introduced in C++11. Since it looks like you’re just learning multithreading it would be useful to learn the standard facilities (which are included with the latest versions of MSVC and GCC) vice vendor-specific APIs.