C++ C++;

C++ C++;,c++,multithreading,class,C++,Multithreading,Class,因此,我对线程基本上是新手,在过去的几周里一直在尝试pthreads。我创建了一个类,它本身有一个线程函数。它工作正常,直到我尝试将类属性(整数)设置为值 .h文件: #ifndef TESTCLASS_H #define TESTCLASS_H #include <iostream> #include <windows.h> using namespace std; class testClass { public: testClass()

因此,我对线程基本上是新手,在过去的几周里一直在尝试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
\ifndef TESTCLASS\u H
#定义TESTCLASS_H
#包括
#包括
使用名称空间std;
类testClass
{
公众:
testClass();
手柄h;
静态DWORD WINAPI mythread(LPVOID参数);
int-mytestint;
作废印刷品();
void startThread();
};
#endif//TESTCLASS\u 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;
}
#包括“testClass.h”
testClass::testClass()
{

cout您实现线程回调的方式不正确。如果您确定它在整数赋值时崩溃,我假设它一定在线程回调的第一行崩溃


您没有在CreateThread函数调用中传递对“this”的引用。

执行线程回调的方式不正确。如果您确定它在整数赋值时崩溃,我假设它一定是在线程回调的第一行崩溃


您没有传递对“this”的引用在CreateThread函数调用中。

您正在使用空指针调用
mythread
。当您将其转换为
This
时,您将在空对象上调用函数。当您执行
mytestint=42
时,计算机会将其视为
This->mytestint=42
,并且由于
This
null
,因此您将其取消引用一个空指针,程序就会出错。您需要执行以下操作:

h = CreateThread(NULL, 0, mythread, (LPVOID)this, 0, NULL);

如果可能的话,我也建议迁移到C++ 11中引入的标准C++线程中。因为它看起来像是在学习多线程,所以学习标准的工具(包括最新版本的MSVC和GCC)是有用的。副供应商特定API。

您正在使用空指针调用mythread
。当您将其转换为This时,您将在空对象上调用函数。当您执行
mytestint=42
时,计算机将其视为
This->mytestint=42
,并且由于
This
null
,因此您将取消引用e一个空指针,程序SEGFULTS。您需要执行以下操作:

h = CreateThread(NULL, 0, mythread, (LPVOID)this, 0, NULL);

如果可能的话,我也建议迁移到C++ 11中引入的标准C++线程中。因为它看起来像是在学习多线程,所以学习标准的工具(包括最新版本的MSVC和GCC)是有用的。特定于副供应商的API。

根据调用约定,在大多数情况下,非虚拟函数调用在您实际尝试读取或写入成员之前不会崩溃。根据调用约定,在大多数情况下,非虚拟函数调用在您实际尝试读取或写入成员之前不会崩溃。好的,它现在可以工作。不要使用使用“this”这样你的解释就有帮助了。谢谢。好的,它现在起作用了。不使用“this”这样你的解释就有帮助了。谢谢。