所以我对一般的线程很陌生,并且在过去的几周里一直在试验 pthreads。我创建了一个内部具有线程函数的类。它工作正常,直到我尝试将类属性(整数)设置为一个值。
.h 文件:
#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 文件
#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;
}
那么为什么我打电话时它会崩溃mytestint = 42;
?