动态线程
简述动态线程的创建和使用方法
主线程创建2个线程t1和t2,创建时2个线程就被挂起,后来调用ResumeThread恢复2个线程,使其开始执行,调用WaitForSingleObject等待2个线程执行完,然后退出主线程即结束进程。
/* file Main.cpp
*
* This program is an adaptation of the code Rex Jaeschke showed in
* Listing 1 of his Oct 2005 C/C++ User's Journal article entitled
* "C++/CLI Threading: Part I". I changed it from C++/CLI (managed)
* code to standard C++.
*
* One hassle is the fact that C++ must employ a free (C) function
* or a static class member function as the thread entry function.
*
* This program must be compiled with a multi-threaded C run-time
* (/MT for LIBCMT.LIB in a release build or /MTd for LIBCMTD.LIB
* in a debug build).
*
* John Kopplin 7/2006
*/
#include <stdio.h>
#include <string> // for STL string class
#include <windows.h> // for HANDLE
#include <process.h> // for _beginthread()
using namespace std;
class ThreadX
{
private:
int loopStart;
int loopEnd;
int dispFrequency;
public:
string threadName;
ThreadX( int startValue, int endValue, int frequency )
{
loopStart = startValue;
loopEnd = endValue;
dispFrequency = frequency;
}
// In C++ you must employ a free (C) function or a static
// class member function as the thread entry-point-function.
// Furthermore, _beginthreadex() demands that the thread
// entry function signature take a single (void*) and returned
// an unsigned.
static unsigned __stdcall ThreadStaticEntryPoint(void * pThis)
{
ThreadX * pthX = (ThreadX*)pThis; // the tricky cast
pthX->ThreadEntryPoint(); // now call the true entry-point-function
// A thread terminates automatically if it completes execution,
// or it can terminate itself with a call to _endthread().
return 1; // the thread exit code
}
void ThreadEntryPoint()
{
// This is the desired entry-point-function but to get
// here we have to use a 2 step procedure involving
// the ThreadStaticEntryPoint() function.
for (int i = loopStart; i <= loopEnd; ++i)
{
if (i % dispFrequency == 0)
{
printf( "%s: i = %d\n", threadName.c_str(), i );
}
}
printf( "%s thread terminating\n", threadName.c_str() );
}
};
int main()
{
// All processes get a primary thread automatically. This primary
// thread can generate additional threads. In this program the
// primary thread creates 2 additional threads and all 3 threads
// then run simultaneously without any synchronization. No data
// is shared between the threads.
// We instantiate an object of the ThreadX class. Next we will
// create a thread and specify that the thread is to begin executing
// the function ThreadEntryPoint(


