I tend to use POSIX Threads, when programming in C, under Linux.
Without MFC
Question:
How would I then create threads in VC++?
Find more information on threads under win32?
I LOVE stackoverflow - best resource for students!
Regards
In main(), we declare a variable called thread_id, which is of type pthread_t, which is an integer used to identify the thread in the system. After declaring thread_id, we call pthread_create() function to create a thread.
The MFC function AfxBeginThread can be called to create a worker thread using the thread function: CWinThread* pThread = AfxBeginThread(MFCThreadProc, NULL); The function AfxBeginThread is passed a pointer to the thread function and a pointer to data to pass to the LPVOID parameter ...
You can also create a thread by calling the CreateRemoteThread function. This function is used by debugger processes to create a thread that runs in the address space of the process being debugged.
In visual basic, the thread is a basic unit of execution within the process and it is responsible for executing the application logic. By default, every application or program will carry one thread to execute the application logic and that thread is called the Main thread.
if you're looking for a platform-independent method, use boost
there's also beginthread() and beginthreadex() functions. Both seem to be supplemental to Win32 API, in a sense that in many use cases, you still need to call some Win32 functions (such as CloseHandle for beginthreadex). So, if you don't care that much about platform compatibility, you might as well cut the foreplay and use CreateThread().
Win32 thread handling is documented here: http://msdn.microsoft.com/en-us/library/ms684852(VS.85).aspx
[edit1] example:
DWORD WINAPI MyThreadProc( void* pContext )
{
return 0;
}
HANDLE h = CreateThread( NULL, 0, MyThreadProc, this, 0L, NULL );
WaitForSingleObject(h, TIME); // wait for thread to exit, TIME is a DWORD in milliseconds
[edit2] CRT & CreateThread():
per MSDN:
A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; this requires the use of the multi-threaded version of the CRT. If a thread created using CreateThread calls the CRT, the CRT may terminate the process in low-memory conditions.
You should not use the raw Win32 CreateThread()
API.
Use the C runtime's _beginthreadex()
so the runtime has an opportunity to set up its own thread support.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With