VC++ 最简单的多线程
发布网友
发布时间:2022-04-24 17:02
我来回答
共2个回答
热心网友
时间:2023-10-24 14:00
#include <windows.h>
#include <iostream>
using namespace std;
DWORD WINAPI MyThread1(PVOID pvParam)
{
for(int a=0;a<10;a++)
{
cout<<"Thread1"<<endl;
Sleep(10000);
}
return 0;
}
DWORD WINAPI MyThread2(PVOID pvParam)
{
for(int b=0;b<3;b++)
{
cout<<"Thread2"<<endl;
Sleep(2000);
}
return 0;
}
DWORD WINAPI MyThread3(PVOID pvParam)
{
for(int c=0;c<7;c++)
{
cout<<"Thread3"<<endl;
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"<<endl;
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这个函数是放弃自己运行的时间片....
热心网友
时间:2023-10-24 14:00
同楼上,稍微补充下,多线程最好用_beginThread和
_beginThreadex,CreateThread运用不当有时候会造成内存泄漏