Hi
I have a problem with using class method as a thread.Can I user a class method as a thread beginning like;
Object o;
_beginthreadex(...,o.DoSomeThing,...);
Thanks
Printable View
Hi
I have a problem with using class method as a thread.Can I user a class method as a thread beginning like;
Object o;
_beginthreadex(...,o.DoSomeThing,...);
Thanks
No, you can't. Not unless that member is static. This is due to incompatibilities of C and C++.
(There are workarounds, though. Typically pass the address of the class as the optional param and call the appropriate function from within the static function.)
Check this out.
Run() is pure virtual.Code:DWORD WINAPI ThreadProxy(void* arg)
{
Thread* thread = static_cast<Thread* >(arg);
thread->Run();
return 0;
}
Thread::Thread()
{
m_thread = CreateThread(NULL, // default security
0, // default stack size
&ThreadProxy, // thread function
this, // thread function argument
0, // default creation flags
0); // don't want thread id
if (m_thread == NULL)
throw Exception("The thread could not be created.");
}
Thread::~Thread()
{
CloseHandle(m_thread);
}
Subclass Thread and implement Run().
Edit:
This is a slight alteration, on Elysia's method. ;)
Code:#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <process.h>
using namespace std;
class Thread
{
public:
void Run();
Thread();
~Thread();
private:
HANDLE m_thread;
};
int main(int argc, char *argv[])
{
Thread thread;
system("PAUSE");
return EXIT_SUCCESS;
}
DWORD WINAPI ThreadProxy(void* arg)
{
Thread* thread = static_cast<Thread* >(arg);
thread->Run();
return 0;
}
void Thread::Run()
{
printf("Selam");
}
Thread::Thread()
{
m_thread = CreateThread(NULL, // default security
0, // default stack size
&ThreadProxy, // thread function
this, // thread function argument
0, // default creation flags
0); // don't want thread id
}
Thread::~Thread()
{
CloseHandle(m_thread);
}
//Thanks
Not quite....
You would have to change Run() everytime you want to do something different....
Something like this is what I was saying.....
ThenCode:virtual void Run() = 0;
Code:class MyThread : public Thread
{
public:
...
void Run();
};
void MyThread::Run()
{
std::cout << "Hello threaded world!" << std::endl;
}
int main(int argc, char* argv[])
{
MyThread thread;
std::cin.get();
return 0;
}
I think a better interface would be a non-inheritable one.
http://www.gotw.ca/publications/mill06.htm
So you would need a "Thread" object that ecapsulates everything needed to run and manipulate a thread.
gg
How about this one?
http://www.boost.org/doc/libs/1_35_0...ml/thread.html
The interface is largely compatible with what will presumably be part of the next C++ standard.