Thread: sending arguments to function using CreateThread

  1. #1
    Registered User Micko's Avatar
    Join Date
    Nov 2003
    Posts
    715

    sending arguments to function using CreateThread

    Is there any way to send more then one parameter to a function using CreateThread.

    Code:
    #include <iostream>
    #include <windows.h>
    using namespace std;
    
    void Func(int *, double);
    
    int main()
    {
    	DWORD ThreadID;
    	int x=1;
    	double y=5.23;
    	HANDLE hThread=CreateThread(0,0,(LPTHREAD_START_ROUTINE)Func,(int *)&x,0,&ThreadID);
    	WaitForSingleObject(hThread,INFINITE);
    	return 0;
    }
    
    
    void Func(int *i,double d)
    {
    	cout<<"Values are: "<<*i<<" i "<<d<<endl;
    }

  2. #2
    Compulsive Liar Robc's Avatar
    Join Date
    Jul 2004
    Posts
    149
    The parameter is a pointer to void, you can send whatever you like if you're sufficiently creative. For example, pass a structure with members representing your arguments.

  3. #3
    Magically delicious LuckY's Avatar
    Join Date
    Oct 2001
    Posts
    856
    What robc said is what is always done. For example (for those who are not as sufficiently creative as Robc suggests), your program would look like this:
    Code:
    #include <iostream>
    #include <windows.h>
    using namespace std;
    
    void Func(LPVOID pArgs_);
    
    struct ARGS {
      int *i;
      double d;
    };
    
    int main()
    {
      DWORD ThreadID;
      int x=1;
      double y=5.23;
      ARGS args = { &x, y };
      HANDLE hThread=CreateThread(0,0,(LPTHREAD_START_ROUTINE)Func,&args,0,&ThreadID);
    	WaitForSingleObject(hThread,INFINITE);
    	return 0;
    }
    
    
    void Func(LPVOID pArgs_)
    {
      ARGS *pArgs = (ARGS*)pArgs_;
      cout<<"Values are: "<<*pArgs->i<<" i "<<pArgs->d<<endl;
    }

  4. #4
    Yes, my avatar is stolen anonytmouse's Avatar
    Join Date
    Dec 2002
    Posts
    2,544
    The only correct prototype for a thread entry function is:
    Code:
    DWORD CALLBACK ThreadProc(LPVOID lpParameter);
    If you have to cast your thread function, you are doing something very wrong.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. dllimport function not allowed
    By steve1_rm in forum C++ Programming
    Replies: 5
    Last Post: 03-11-2008, 03:33 AM
  2. Arrays as function arguments :(
    By strokebow in forum C Programming
    Replies: 10
    Last Post: 11-18-2006, 03:26 PM
  3. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  4. Replies: 10
    Last Post: 09-27-2005, 12:49 PM
  5. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM