• Coding
  • [C++] _beginthread() with function that takes parameters

Okay so here's the problem. I'm trying some new (to me) concepts in multithreaded programming in c++, and I got to this freaking problem. I'm using process.h, and the _beginthread() function to call my functions. It works like a charm, and i've learned to use the critical section to suit my needs till now. Problem is, I don't know how to pass functions that take parameters to the _beginthread() function... anyways this is what i'm trying to do. its not nearly done, just a proof of concept, so all i want is to know how to call the second function that takes a char parameter, if it can be done.
#include <iostream>
#include <cstdlib>
#include <windows.h>
#include <conio.h>
#include <process.h>

using namespace std;

HANDLE hOut;
COORD Position;

char keys;

void choice (void *);
void verk (void *);

int main()
{
    getch();
    _beginthread(choice,
                 0,
                 NULL);
    _beginthread(verk,
                 0,
                 NULL);
    return 0;
}

void verk (char key, void *P){

    switch(key){

        case 'd':
                Position.X++;
                break;
        case 'a':
                Position.X--;
                break;
        case 'w':
                Position.Y++;
                break;
        case 's':
                Position.Y--;
                break;
        case 'q':
                system("exit");
        default : break;
    }

    hOut=GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleCursorPosition(hOut, Position);
    cout<<"s";
    Sleep(200);
}

void choice(void *P){
keys=getch();
}
The _beginthread() function has a parameter called arglist. You use that to pass arguments to your functions. In your code, you're always passing this as NULL.

The holy MSDN specifies the following prototype for _beginthread:
uintptr_t _beginthread( 
   void( *start_address )( void * ),
   unsigned stack_size,
   void *arglist 
);
So what I would do is keep the prototype for verk as:
void verk(void *k);
And in main do:
char c = getchar();
_beginthread(verk, 0, &c);
and then in the body of verk do:
char key = *((char *)k);
switch(key) { .. }
...
This code is probably a bit flawed since I don't have Windows or the right tools to test it, but you get the idea. Also, why use conio.h, is there some special functionality it's providing? I just replaced your getch() with getchar() which is available in standard C, but you could also use cin.

In this way you would have passed an argument to your thread. You can extend this method to pass multiple arguments if you need but it's one in the morning and I can't think of how. :)
if you want to pass multiple arguments you use a pointer to a struct.