企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# Win32多线程程序设计-同步控制 ``` #include "pch.h" //#include <iostream> #include "windows.h" #include "stdio.h" bool flag; CRITICAL_SECTION cs; DWORD WINAPI Thread1_Proc(PVOID pvParam) { while (1) { do { ; } while (1 == flag); EnterCriticalSection(&cs); printf("Hello,"); LeaveCriticalSection(&cs); flag = 1; Sleep(50); } } DWORD WINAPI Thread2_Proc(PVOID pvParam) { while (1) { do { ; } while (0 == flag); EnterCriticalSection(&cs); printf("World!\n"); LeaveCriticalSection(&cs); flag = 0; Sleep(50); } } int main(int argc, char* argv[]) { DWORD nID; InitializeCriticalSection(&cs); CreateThread(NULL, 0, Thread1_Proc, NULL, 0, NULL); CreateThread(NULL, 0, Thread2_Proc, NULL, 0, NULL); while (1) { ; } DeleteCriticalSection(&cs); return 0; } ``` //改进了一下!: ``` #include "pch.h" //#include <iostream> #include "windows.h" #include "stdio.h" char flagc = '.';// | ';// .'; bool flag; CRITICAL_SECTION cs; DWORD WINAPI Thread1_Proc(PVOID pvParam) { while (1) { // while (1 == flag); while ('.' == flagc) { Sleep(1);} EnterCriticalSection(&cs); printf("["); for (int i = 0; i < 19159; ++i) { printf("."); //printf("[%d]" , i); }//[i%d]", i); } printf("]\r\n"); LeaveCriticalSection(&cs); flagc = '.';// flag = 1; Sleep(50); } } DWORD WINAPI Thread2_Proc(PVOID pvParam) { while (1) { while ('|' == flag) { Sleep(2);}//while (0 == flag) { Sleep(2);} EnterCriticalSection(&cs); printf("<"); for(int j=0;j<9149;++j) {printf("|%d|",j);} printf(">\r\n"); LeaveCriticalSection(&cs); flagc = '|';// flag = 0; Sleep(50); } } int main(int argc, char* argv[]) { DWORD nID; InitializeCriticalSection(&cs); CreateThread(NULL, 0, Thread1_Proc, NULL, 0, NULL); CreateThread(NULL, 0, Thread2_Proc, NULL, 0, NULL); while (1) { ; } DeleteCriticalSection(&cs); return 0; }//main() ```