下面我有一个int main()
和两个头文件,其中一个是用于创建线程的类,另一个是在object
类中创建的名为windows_thread
的类。这个非常简单的练习应该输出99而不是1(由于某种未知的原因)。我还尝试使用指向由new
制作的对象的指针,当void call()
从函数Thread_no_1( )
到类object
时,该对象崩溃,可能是因为它不存在。我希望有人可以解决这个问题,否则我只会在int main()
中使用Windows线程。
这是主要的。
#include "windows_thread.h"
int main()
{
windows_thread* THREAD = new windows_thread();
THREAD->thread();
delete THREAD;
return 0;
}
这是windows_thread.h
#include <windows.h>
#include <stdio.h>
#include "object.h"
#define BUF_SIZE 255
class windows_thread
{
object OBJECT;
public:
windows_thread():OBJECT(99)
{
//OBJECT = new object(99);
}
~windows_thread()
{
//delete OBJECT;
}
void thread()
{
std::cout<<"void thread: "<<std::endl;
int Data_Of_Thread_1 = 1; // Data of Thread 1
HANDLE Handle_Of_Thread_1 = 0; // variable to hold handle of Thread 1
HANDLE Array_Of_Thread_Handles[1]; // Aray to store thread handles
// Create thread 1.
Handle_Of_Thread_1 = CreateThread( NULL, 0, Wrap_Thread_no_1, &Data_Of_Thread_1, 0, NULL);
if ( Handle_Of_Thread_1 == NULL) ExitProcess(Data_Of_Thread_1);
// Store Thread handles in Array of Thread Handles as per the requirement of WaitForMultipleObjects()
Array_Of_Thread_Handles[0] = Handle_Of_Thread_1;
// Wait until all threads have terminated.
WaitForMultipleObjects( 1, Array_Of_Thread_Handles, TRUE, INFINITE);
printf("Since All threads executed lets close their handles \n");
// Close all thread handles upon completion.
CloseHandle(Handle_Of_Thread_1);
}
void DisplayMessage (HANDLE hScreen, char *ThreadName, int Data, int Count)
{
TCHAR msgBuf[BUF_SIZE];
size_t cchStringSize;
DWORD dwChars;
// Print message using thread-safe functions.
//StringCchPrintf(msgBuf, BUF_SIZE, TEXT("Executing iteration %02d of %s having data = %02d \n"), Count, ThreadName, Data);
//StringCchLength(msgBuf, BUF_SIZE, &cchStringSize);
WriteConsole(hScreen, msgBuf, cchStringSize, &dwChars, NULL);
Sleep(1000);
}
DWORD WINAPI Thread_no_1( )
{
std::cout<<"Thread_no_1: "<<std::endl;
OBJECT.call();
//OBJECT->call();
return 0;
}
static DWORD WINAPI Wrap_Thread_no_1( LPVOID lpParam )
{
std::cout<<"Wrap_Thread_no_1: "<<std::endl;
windows_thread *self = reinterpret_cast<windows_thread*>(lpParam);
self->Thread_no_1();
return 0;
}
};
接下来是object.h
#ifndef OBJECT_H
#define OBJECT_H
#include <iostream>
class object
{
private:
int value;
public:
object(int value)
{
std::cout<<"object::constructor: "<<std::endl;
this->value = value;
}
~object(){}
void call()
{
std::cout<<"object::call(): begin"<<std::endl;
std::cout<<value<<std::endl;
std::cout<<"object::call(): end"<<std::endl;
}
};
#endif
答案 0 :(得分:4)
此函数调用:
Handle_Of_Thread_1 = CreateThread(
NULL,
0,
Wrap_Thread_no_1,
&Data_Of_Thread_1, // <== THIS IS A POINTER TO AN int
0,
NULL
);
将&Data_Of_Thread_1
(指向int
的指针)传递给CreateThread()
。这是最终传递给Wrap_Thread_no_1()
的参数。
在该函数中,然后将该指针强制转换为windows_thread*
并通过它调用成员函数。这会在您的代码中注入未定义的行为。
您可能打算这样做:
Handle_Of_Thread_1 = CreateThread(NULL, 0, Wrap_Thread_no_1, this, 0, NULL);
// ^^^^