- C/C++ code
#include<stdio.h>#include <Windows.h>long g_x=0;DWORD WINAPI ThreadProc(PVOID pvParam){ InterlockedExchangeAdd(&g_x,1); return 0;}DWORD WINAPI ThreadProc2(PVOID pvParam){ InterlockedExchangeAdd(&g_x,1); return 0;}int main(){ HANDLE hTherad[2]; hTherad[0]=CreateThread(NULL,0,ThreadProc,0,0,0); hTherad[1]=CreateThread(NULL,0,ThreadProc2,0,0,0); printf("%ld\n",g_x); CloseHandle(hTherad[0]); CloseHandle(hTherad[1]); return 0;}
原子锁。是绑订一个硬件信号。防制其它CPU去访问这个线程。为什么我这里没有实现同步呢??
------解决方案--------------------------------------------------------
主线程很快就退出了,进程也就结束了;
------解决方案--------------------------------------------------------
在主线程加个同步等待