C++ 类:创建线程的对象 + 指向函数的指针 = 访问冲突

问题描述:

我对我得到的奇怪异常感到非常惊讶.

I am very surprised by the strange exception, that I got.

class Threads { 
    public:
        Threads() {}
        ~Threads() {}
        void StartThread(int (*p)()); //pointer to a function 
    private: 
        HANDLE hThread; 
        DWORD dwThreadID; 
    }; 

方法 StartThread 应该接收指向我的函数的指针(将在另一个线程中运行).
这个功能很简单.(如您所见,它位于 Threads 类之外):

Method StartThread should receive pointer to my function (that will be run in another thread).
This function is simple. (as you can see it is situated outside the class Threads):

int MyThread() 
{
return 0; 
}

这是创建线程的方法:

inline void Threads::StartThread(int (*p)()) 
{
    hThread = CreateThread(NULL, 
            0, 
            (LPTHREAD_START_ROUTINE)(*p)(), 
            NULL,  
            0, 
            &dwThreadID); 

   if (hThread == NULL) 
        {
            return;
        }
}

此处编译器出错:无法将参数 3 从int"转换为LPTHREAD_START_ROUTINE".这就是我进行选角的原因.

Here compiler get error: cannot convert parameter 3 from 'int' to 'LPTHREAD_START_ROUTINE'. That why I did the casting.

在主函数中,我创建了 Threads 类型的对象,并尝试调用方法 StartThread.作为参数,我发送指向函数 MyThread 的指针.

In main function I create object of type Threads and I try to call method StartThread. As parameter I send pointer to the function MyThread.

Threads *thread1; 
thread1 = new Threads(); 
thread1->StartThread(MyThread);

我认为 MyThread 必须在另一个线程中启动.但是MyTread函数总是在主线程中运行!!!只有在 MyThread 结束后,另一个线程才开始,然后我得到这个异常:ThreadClass.exe 中 0x00000000 处的未处理异常:0xC0000005:访问冲突.

I thought MyThread must start in another thread. But the function MyTread always runs in Main Thread!!! And only after MyThread ends, another thread starts and then I get this exception: Unhandled exception at 0x00000000 in ThreadClass.exe: 0xC0000005: Access violation.

我需要聪明的建议!

看起来你实际上是在调用这一行的函数...

It looks like you are actually calling the function on this line...

(LPTHREAD_START_ROUTINE)(*p)()

...它返回一个你正在转换的整数.那是行不通的.怎么样:

...and it returns an int that you're casting. That just can't work. How about:

(LPTHREAD_START_ROUTINE)p 

...相反?