C++ 多线程 CreateThread函数使用例

发布于:2021-05-15 06:34:56

#include
#include
#include
#include
#include
#include
#include
//头文件引用较多, 有一些与本程序无关

/*
HANDLE WINAPI CreateThread(
LPSECURITY_ATTRIBUTES lpThreadAttributes, //线程安全相关的属性,常置为NULL
SIZE_T dwStackSize, //新线程的初始化栈在大小,可设置为0
LPTHREAD_START_ROUTINE lpStartAddress, //被线程执行的回调函数,也称为线程函数
LPVOID lpParameter, //传入线程函数的参数,不需传递参数时为NULL
DWORD dwCreationFlags, //控制线程创建的标志
LPDWORD lpThreadId //传出参数,用于获得线程ID,如果为NULL则不返回线程ID
);
*/

using namespace std;

//volatile是一个类型修饰符,表示这变量可能会被意想不到地改变,这样,编译器就不会去假设这个变量的值了
volatile int b = 0;
//int b = 0;

DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
int i = 10000;
int *p = (int*)lpParameter;
while(i--)
{
(*p)++;
b++;
}

return 0;
}

int main(int argc, char* argv[])
{
int a = 0;

HANDLE hThread1 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL);
HANDLE hThread2 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL);
HANDLE hThread3 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL);
HANDLE hThread4 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL);
HANDLE hThread5 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL);

Sleep(1000);

CloseHandle(hThread1);
CloseHandle(hThread2);
CloseHandle(hThread3);
CloseHandle(hThread4);
CloseHandle(hThread5);

cout << "a = " << a << endl;
cout << "b = " << b << endl;

system("pause");
return 0;
}

执行多次, 结果a,b的值都是50000......

相关推荐

最新更新

猜你喜欢