Girl_Developer
Girl_Developer

Reputation: 3

C++ Class: Object that creates Thread + pointer to the function = Access violation

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; 
    }; 

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; 
}

And this is method of creating thread:

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

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

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

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);

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.

I need clever advice!

Upvotes: 0

Views: 1142

Answers (2)

executifs
executifs

Reputation: 1178

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 

...instead?

Upvotes: 0

Kevin
Kevin

Reputation: 25269

The call convention is wrong:

LPTHREAD_START_ROUTINE is a __stdcall method not a __cdecl method, see the documentation here: http://msdn.microsoft.com/en-us/library/aa964928.aspx.

Upvotes: 2

Related Questions