难道我对volatile关键字的理解以前都是错误的?
请看代码
volatile int tickets=0;volatile BOOL g_bRun = TRUE;DWORD WINAPI Fun1Proc(LPVOID lpParameter){ char buf[100]; while(g_bRun) { if(tickets<10) { sprintf(buf,"\nthread1 sell ticket = %d",tickets); OutputDebugString(buf); printf(buf); tickets++; } else Sleep(10); } return 0;}DWORD WINAPI Fun2Proc(LPVOID lpParameter){ char buf[100]; while(g_bRun) { if(tickets<10) { sprintf(buf,"\nthread2 sell ticket = %d",tickets); OutputDebugString(buf); printf(buf); tickets++; } else Sleep(10); } return 0;}int main(int argc, char* argv[]){ CreateThread(NULL,0,Fun1Proc,NULL,0,NULL); CreateThread(NULL,0,Fun2Proc,NULL,0,NULL); Sleep(2000); system("PAUSE"); g_bRun = FALSE; return 0;}thread2 sell ticket = 0thread1 sell ticket = 1thread2 sell ticket = 2thread1 sell ticket = 3thread2 sell ticket = 4thread1 sell ticket = 5thread2 sell ticket = 6thread1 sell ticket = 7thread2 sell ticket = 8thread1 sell ticket = 9
thread1 sell ticket = 0thread1 sell ticket = 0thread2 sell ticket = 0thread1 sell ticket = 1thread2 sell ticket = 2thread1 sell ticket = 3thread2 sell ticket = 4thread1 sell ticket = 5thread2 sell ticket = 6thread1 sell ticket = 7thread2 sell ticket = 8thread1 sell ticket = 9