Take a look at the code first:
#include <Windows.h> #include <stdio.h>int x, y, R1, R2; HANDLE Event1, Event2, EventMain1, Eventmain2;dword_stdcallthreadproc1 (LPVOID lpthreadparameter) {while (TRUE ) {WaitForSingleObject (Event1, INFINITE); while (rand ()% 8! = 0); x = 1; R1 = y; SetEvent (EventMain1); }}DWORD_STDCALLTHREADPROC2 (LPVOID lpthreadparameter) {while (TRUE) {WaitForSingleObject (Event2, Infin ITE); while (rand ()% 8! = 0); y = 1; r2 = x; SetEvent (EventMain2); }}void Main () {HANDLE Thread1, Thread2; Thread1 = CreateThread (null, 0, ThreadProc1, NULL, 0, NULL); Thread2 = CreateThread (null, 0, THREADPROC2, NULL, 0, NULL); Setthreadaffinitymask (Thread1, 1); Setthreadaffinitymask (Thread2, 2); Event1 = CreateEvent (null, FALSE, FALSE, NULL); Event2 = CreateEvent (null, FALSE, FALSE, NULL); EventMain1 = CreateEvent (null, FALSE, FALSE, NULL); EventMain2 = CreateEvent (NULL, FALSE, FALSE, NULL); int dectected = 0; for (int i = 0;; i++) {x = 0; y = 0; SetEvent (EVENT1); SetEvent (Event2); WaitForSingleObject (EventMain1, INFINITE); WaitForSingleObject (EventMain2, INFINITE); if (r1 = = 0 && r2 = = 0) {printf ("detected%d, I%d\n", dectected++, I); } }}
Describe the focus of this code, starting with two threads executing on two CPU cores, performing x = 1, r1= y, respectively; y = 1, r2 = x; no matter which thread executes first, or executes together, the common sense execution results generally r1 = 1 or r2 = 1 or two are 1, that is, in the main function of the judgment R1 and R2 with 0 of the judgment is impossible to set up, printing will not appear.
When you're really running on at least one dual-core machine, you shouldn't believe your eyes.
Detected 305, I 202654detected 306, I 204704detected 307, I 205029detected 308, I 206454detected 309, I 207135detected 310 , I 208178detected 311, I 208610detected 312, i 208879detected 313, I 208896detected 314, I 208960detected 315, I 209003de tected, I 209869detected 317, I 210573detected 318, I 211259detected 319, I 211275detected, I 211487detected 321, I 212646detected 322, I 212963detected 323, I 213317detected 324, I 213382detected 325, I 213473detected 326, I 213588dete CTED 327, I 214940detected 328, I 215055detected 329, I 215271
(Because the map is not convenient, directly to the printer copy down)
From the printing can be drawn, after two threads run, r1== r2 = = 0 situation actually appeared, is the CPU is teasing us.
CPU does not tease us, is we do not understand it. adjourned
Talking about Cache