passing multiple params to thread

I have a function like such:
void acceptClients(CLIENTS *list,SOCKET s)

and I want to run it in a thread, something like:
_beginthread(acceptingClients,0,thisList,thisS);

but of course that's not going to work. I tried:
1
2
3
4
	void *pList[2];
	pList[0]=(void*)clientList;
	pList[1]=(void*)controlSocket;
	_beginthread(acceptingClients,0,pList);


but still no luck. How do I pass multiple parameters to a thread function?
Can you just create a struct with multiple fields in it, then pass a pointer to the struct to the thread?
I don't quite understand what you are trying to do. You mean do something like this?

createthread(threadfunc(param1, param2), ...)

If so, I don't think you can...you could try creating the thread with a dummy function that simply calls another function and passes parameters to that one, like this:

1
2
3
4
5
6
7
8
9
10
11
WINAPI dummyfunc(void) {
      realfunc(...);
}

void realfunc(...) {
      //do stuff
}

int main() {
     CreateThread(/*...*/, (LP_START_ROUTINE) dummyfunc, /*...*/);
}
Last edited on
This is what I was suggesting:

1
2
3
4
5
6
7
8
9
10
struct ThreadParams {
    explicit ThreadParams( CLIENTS* c = 0, SOCKET s = -1 ) : 
        clients( c ), sock( s ) {}

    CLIENTS*  clients;
    SOCKET    sock;
}

ThreadParams* params = new ThreadParams( clientList, controlSocket );
_beginthread( acceptingClients, 0, params );

jsmith, that is much closer to what i want to do. I have a struct like that, but idon't have the xplicit part in it. Could you explain the :

1
2
explicit ThreadParams( CLIENTS* c = 0, SOCKET s = -1 ) : 
        clients( c ), sock( s ) {}


I don't see what that does exactly. thanks!
The explicit keyword can be used any time you write a constructor that could take exactly one parameter. It basically says to the compiler that the compiler cannot use that constructor for implicit type conversion. Let's say you have the following object and constructor:

1
2
3
4
struct  ObjectA {
    ObjectA( int x ) : ex( x ) {}
    int ex;
};



Now let's say you have a function Foo() that takes an ObjectA as parameter:
 
void Foo( ObjectA a ) {}



You can call Foo() with either an ObjectA instance or an int. If you call it with an int, the compiler will construct a temporary ObjectA from the int using ObjectA's constructor.

Sometimes you don't want the compiler to do that. Especially if you have a lot of objects that have constructors that take one parameter. You can get a lot of implicit conversion going on.

As for the colon in the line above, that is an initializer list. It is _usually_ equivalent to

1
2
3
4
explicit ThreadParams( CLIENTS* c = 0, SOCKET s = -1 ) {
    clients = c;
    sock = s;
}


However it is always better to initialize members in an initializer list than in the body of the constructor.

Topic archived. No new replies allowed.