volatile 用法
#include <iostream>
#include <windows.h>
#include <stdio.h>
volatile int WorkerID = 10; // volatile被设计用来修饰被不同线程访问和修改的变量
const int MAXWORKERID = 100;
DWORD __stdcall ThreadFunOne(LPVOID lParam)
{
for (;;)
{
if (WorkerID < MAXWORKERID)
{
WorkerID += 1;
Sleep(1000);
printf("ThreadOne print out: %i \\n", WorkerID);
}
}
return 0;
}
DWORD __stdcall ThreadFunTwo(LPVOID lParam)
{
for (;;)
{
if (WorkerID < MAXWORKERID)
{
WorkerID += 1;
Sleep(1000);
printf("ThreadTwo print out: %i \\n", WorkerID);
}
}
return 0;
}
int main()
{
HANDLE hThread1, hThread2;
// Create thread
hThread1 = ::CreateThread(NULL, 0, ThreadFunOne, NULL, 0, NULL);
hThread2 = ::CreateThread(NULL, 0, ThreadFunTwo, NULL, 0, NULL);
// Close thread handle
CloseHandle(hThread1);
CloseHandle(hThread2);
// Note: Prevent process exiting
while (true)
{
;
}
return 0;
}