I have an array of objects and want each one to call a member function in a separate thread (so they run concurrently). I'm using _beginthreadex
and can get it to work fine for a standard function but can't figure out the syntax to pass the member function to the _beginthreadex
call. Here's an example of what I'm doing (the block of code after the second comment does not compile):
#include <Windows.h>
#include <process.h>
#include <stdio.h>
unsigned __stdcall mythread(void* data) {
printf("\nThread %d", GetCurrentThreadId());
return 0;
}
class myClass {
public:
unsigned __stdcall myClass::myThread(void* data);
};
unsigned __stdcall myClass::myThread(void* data) {
printf("\nThread %d", GetCurrentThreadId());
return(0);
}
int main(int argc, char* argv[]) {
int i, numThreads = 5;
// this works
HANDLE *myHandle = new HANDLE[numThreads];
for(i=0;i<numThreads;i++) myHandle[i] = (HANDLE)_beginthreadex(0, 0, &mythread, 0, 0, 0);
WaitForMultipleObjects(numThreads, myHandle, true, INFINITE);
for(i=0;i<numThreads;i++) CloseHandle(myHandle[i]);
getchar();
delete myHandle;
// this does not compile - not sure of syntax to call myObject[i].myThread in _beginthreadex
HANDLE *myHandle2 = new HANDLE[numThreads];
myClass *myObject = new myClass[numThreads];
for(i=0;i<numThreads;i++) myHandle2[i] = (HANDLE)_beginthreadex(0, 0, &myObject[i].myThread, 0, 0, 0);
WaitForMultipleObjects(numThreads, myHandle2, true, INFINITE);
for(i=0;i<numThreads;i++) CloseHandle(myHandle2[i]);
getchar();
delete myObject;
delete myHandle2;
return 0;
}
Thanks in advance for any help!
rgames