【原创】CreateThread创建一个简单的多线程
创建一个Win32 Console Application,工程名为CreateMythread
添加一个CPP文件,代码如下
#include <iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI ThreadProc(LPVOID pParam);
UINT PrintHello(LPVOID lpParam);
HANDLE g_Mutex; //互斥量
int main(int argc,char* argv[])
{
//创建互斥量
g_Mutex=CreateMutex(NULL,false,"CreateMythread");
DWORD ThreadID;
char* cParam="Hello World!";
int iParam=2010;
//创建第一个线程ThreadProc
CreateThread(NULL,0,ThreadProc,
cParam,0,&ThreadID);
//创建第二个线程PrintHello
//若不是规范格式则必须用LPTHREAD_START_ROUTINE转换
CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)PrintHello,
&iParam,0,&ThreadID);
Sleep(100);
CloseHandle(g_Mutex);
//system("pause");
return 0;
}
DWORD WINAPI ThreadProc(LPVOID pParam)
{
//等待被唤醒
WaitForSingleObject(g_Mutex,INFINITE);
cout <<"CreateThread:ThreadProc ";
cout <<(char*)pParam <<endl;
//Sleep(0);
//将互斥量设置为有信号,此时第一个等待的线程被唤醒,并将该互斥量置为无信号状态
ReleaseMutex(g_Mutex);
return 0;
}
UINT PrintHello(LPVOID lpParam)
{
WaitForSingleObject(g_Mutex,INFINITE);
cout <<"CreateThread:PrintHello ";
cout <<*((int*)lpParam) <<endl;
//Sleep(0);
ReleaseMutex(g_Mutex);
return 0;
}