I'm confusing how to pass a argument into the thread function.After studying some documents about the thread, i wrote a program which could run correctly about the argument passing.But i feel that the code contains some potential dangers, for i must change the pointer point to the argument to void*, whick will be changed back in the thread function.
Do you have any better and safer ways to pass the arguments?
the source code:
Code:
/*
传的是指针,对于某结构,先将其指针转化为void*, 再在线程函数的内部转化回来
*/
#include <windows.h>
#include <process.h> /* _beginthread, _endthread */
//#include <stddef.h>
#include <stdlib.h>
#include <conio.h>
#include <iostream>
using std::cout;
using std::endl;
bool repeat = true;
unsigned __stdcall test(void* pArguments) {
int* array = (int*)pArguments;
while (repeat) {
cout << array[1] << endl;
Sleep(500);
}
_endthreadex(0);
return 0;
}
unsigned __stdcall check(void* pArguments) {
getch();
repeat = false;
_endthreadex(0);
return 0;
}
int main() {
unsigned threadID[2];
int array[] = {45, 34, 57};
HANDLE checkHandle = (HANDLE)_beginthreadex(NULL, 0, &check, NULL, 0, &threadID[0]);
HANDLE textHandle = (HANDLE)_beginthreadex(NULL, 0, &test, (void*)(array), 0, &threadID[1]);
WaitForSingleObject(textHandle, INFINITE);
CloseHandle(checkHandle);
CloseHandle(textHandle);
return 0;
}