-
Threads
I found an example on threads but I'm having trouble ripping it to a new project....
Code:
#include <iostream.h>
#include <fstream.h>
#include <time.h>
#include <windows.h>
HANDLE HThread;
unsigned long ThreadH;
unsigned long _stdcall getchthread(void* data);
int main()
{
HThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)getchthread,(LPVOID)0,0,&ThreadH);
TerminateThread(HThread,0);
return 0;
}
unsigned long _stdcall getchthread(void* data)
{
while(1)
{
cout<<"HELLO"<<endl;
}
return 0;
}
what am I missing :confused:
-
Well, it did exactly what I expected it to do (nothing :D).
You don't give the thread time to actually *do* anything. Try this (with some minor tweaks):
Code:
#include <iostream>
#include <fstream>
#include <ctime>
#include <windows.h>
using namespace std;
HANDLE HThread;
unsigned long ThreadH;
unsigned long _stdcall getchthread(void* data);
int main() {
HThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)getchthread,(LPVOID)0,0,&ThreadH);
Sleep(3000);
TerminateThread(HThread,0);
return 0;
}
unsigned long _stdcall getchthread(void* data) {
while(1) {
cout << "HELLO" << endl;
Sleep(500);
}
return 0;
}
-
You shouldn't terminate a thread using TerminateThread. You should rather send a signal like here:
Code:
#include <iostream>
#include <fstream>
#include <ctime>
#include <windows.h>
using namespace std;
HANDLE HThread;
unsigned long ThreadH;
unsigned long _stdcall getchthread(void* data);
int main() {
bool *pEnd = new bool;
*pEnd = false;
HThread = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)getchthread,pEnd,0,&ThreadH);
Sleep(3000);
*pEnd = true;
// allow thread to terminate
WaitForSingleObject(HThread, INFINITE);
return 0;
}
unsigned long _stdcall getchthread(void* data) {
while(!*(bool*)data) {
cout << "HELLO" << endl;
Sleep(500);
}
return 0;
}
There is a small difference between parksie's includes and yours: the extension. You way is deprecated, use the new one.