VC++ 最简单的多线程

2024-11-27 14:41:49
推荐回答(2个)
回答1:

#include
#include
using namespace std;

DWORD WINAPI MyThread1(PVOID pvParam)
{
for(int a=0;a<10;a++)
{
cout<<"Thread1"< Sleep(10000);
}
return 0;
}

DWORD WINAPI MyThread2(PVOID pvParam)
{
for(int b=0;b<3;b++)
{
cout<<"Thread2"< Sleep(2000);
}
return 0;
}

DWORD WINAPI MyThread3(PVOID pvParam)
{
for(int c=0;c<7;c++)
{
cout<<"Thread3"< Sleep(7000);
}
return 0;
}
int main()
{
HANDLE hThread1 = CreateThread(NULL, 0, MyThread1, NULL, 0, NULL);
HANDLE hThread2 = CreateThread(NULL, 0, MyThread2, NULL, 0, NULL);
HANDLE hThread3 = CreateThread(NULL, 0, MyThread3, NULL, 0, NULL);
Sleep(5000);
cout<<"Main"< CloseHandle(hThread1);
CloseHandle(hThread2);
CloseHandle(hThread3);
return 0;
}

首先创建一个线程实用API CreateThread , 还有就是一个线程函数的原型.
HANDLE CreateThread(
LPSECURITY_ATTRIBUTES lpsa,
DWORD cbStack,
LPTHREAD_START_ROUTINE lpStartAddr,
LPVOID lpvThreadParam,
DWORD fdwCreate,
LPDWORD lpIDThread
);

DWORD WINAPI ThreadProc(
[in] LPVOID lpParameter
);

还有就是Sleep这个函数是放弃自己运行的时间片....

回答2:

同楼上,稍微补充下,多线程最好用_beginThread和
_beginThreadex,CreateThread运用不当有时候会造成内存泄漏