-
Win32 Threading
Im trying to make a Non-Blocking Server/Client Program using Winsock and Im trying to create threads to handle the blocking functions.
I was wondering, how do I actually set up a simple thread?
If anybody knows of an example that uses Threading, in C if possible, Id greatly appreciate it.
Basically i just need a skeleton app that demonstrates starting/creating a thread on the click of a button, and then ending/destroying that thread on the click of another button.
I have a basic layout but i have no idea what to do, Ive tried but my programs take up 100% of my CPU and It takes me 10 minutes of clicking on the X button to close them.
Code:
Winmain()
{
...
}
Winproc()
{
case WM_COMMAND:
{
switch(HIWORD(wParam))
{
case BN_CLICKED:
{
switch(LOWORD(wParam))
{
case START_THREAD:
{
//code here to start thread
break;
}
case STOP_THREAD:
{
//code here to stop thread
break;
}
}
break;
}
}
break;
}
}
void Thread1()
{
//Lets say it make the titlebar scroll
}
void Thread2()
{
//Lets say it make the titlebar flash
}
I just need someone to fill in the blanks (more or less), and if possible can you show an example of setting up 2 threads at the same time.
-
Here is a good place to start.
Once you know what API's you'll be dealing with, you can look em up on MSDN or search the boards.
gg
-
Code:
// CreateThread.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <windows.h>
void ThreadFunc(LPVOID data);
int _tmain(int argc, _TCHAR* argv[])
{
DWORD threadID;
TCHAR msg[] = "Hello from another thread!";
//Create a run of the mill thread
HANDLE hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadFunc,
(LPVOID)msg, 0, &threadID);
//Wait for the thread to finish. In a real program you would probably
//want to do something here
WaitForSingleObject(hThread,INFINITE);
//Free the handle back to Windows
CloseHandle(hThread);
return 0;
}
void ThreadFunc(LPVOID data)
{
TCHAR *msg = (TCHAR*)data;
MessageBox(NULL, msg, _T("Yo!"), MB_OK | MB_ICONINFORMATION);
}
tmode -nopause
-
Just as a side note. If your Class is contained within a class, i dont believe you can call a class function for your Start Routine. just something i ran into recently. Way i got around it was i created a function outside the class which just called the class functions. I couldn't find excact reason for not being able to call it directly, so i did that. :P
-
You can also just make the thread function a static function of your class.
-
I highly recommend Network Programming for Microsoft Windows, Second Edition by Anthony Jones and Jim Ohmund.
Check out CodeProject code section for examples on winsock. Check out my website for more winsock links.
http://www.dslextreme.com/users/kuphryn/links.html
Kuphryn