Thread Error

CODE:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
class Secure {
private:
  int seconds;
  bool isRUNNING;
public:
  Secure(int seconds) {
    this->seconds = seconds;
    isRUNNING = true;
  }
  void doSCAN() {
    while (isRUNNING) {
    //SCAN_CODE_HERE
    }
  }
}

void PROTECT() {
  Secure secure = new Secure(5);
  DWORD sHandle = NULL;
  ::CreateThread(NULL, NULL, &secure->doSCAN, NULL, 0, NULL);
}

int main() {
  PROTECT();
  while (true) {
    //DO_PROGRAM
  }
  return 0;
}


ERROR:
 
error C2276: '&' : illegal operation on bound member function expression


I read that due to explicit casting, threads cannot be created within a class.
I'm trying to thread a scanning system to relieve stress on my main program/module, rather than having the scanner stunt their performance.
Last edited on
Before anyone asks me why not drop the & operator, it's a necessity to reference the method.
CreateThread is part of a C api. You cannot pass a pointer to a C++ member function to CreateThread (and if you could, your syntax would be wrong as indicated by the error message.)

Pointer to member functions are sometimes larger than C function pointers (as well as having different calling conventions) and there is no guarantee it will fit into a void pointer.
Last edited on
Pointer to member functions are sometimes larger than C function pointers (as well as having different calling conventions) and there is no guarantee it will fit into a void pointer.
Hm?

A member function looks like this:

void object->member_function(...) -> void member_function(object *this, ...)

i.e. the first parameter is the pointer to the object.

you cannot pass a member function of a class to CreateThread because of the different signature

To solve the problem you need a function of the required signature:

http://msdn.microsoft.com/en-us/library/windows/desktop/ms686736%28v=vs.85%29.aspx

1
2
3
4
5
6
7
8
9
DWORD ThreadProc(
  LPVOID lpParameter
)
{
((Secure *) lpParameter)->doSCAN();
return 0;
}

::CreateThread(NULL, NULL, &ThreadProc, secure, 0, NULL);
Last edited on
cire wrote:
Pointer to member functions are sometimes larger than C function pointers (as well as having different calling conventions) and there is no guarantee it will fit into a void pointer.
coder777 wrote:
Hm?


http://ideone.com/Q7fS61

http://blogs.msdn.com/b/oldnewthing/archive/2004/02/09/70002.aspx

Note that if the only barrier to using a member function pointer was the signature, feeding one to CreateThread would be trivial, since a pointer-to-class will fit into a void pointer, but both calling convention and pointer sizes may vary for member functions.
Last edited on
Topic archived. No new replies allowed.