AtomicOperation

// AtomicOperation.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <windows.h>


//所谓原子操作是指不会被线程调度机制打断的操作;这种操作一旦开始,就一直运行到结束,中间不会有任何 context switch (切换到另一个线程)。
LONG g_iFree{};
LONG g_iAtomic{};
DWORD WINAPI ThreadProc1(LPVOID lpThreadParameter);
DWORD WINAPI ThreadProc2(LPVOID lpThreadParameter);


int main()
{
	HANDLE hThread[2]{};
	hThread[0] = CreateThread(0, 0, ThreadProc1, 0, 0, 0);
	hThread[1] = CreateThread(0, 0, ThreadProc2, 0, 0, 0);

	WaitForMultipleObjects(2, hThread, TRUE, INFINITE);
	CloseHandle(hThread[0]);
	CloseHandle(hThread[1]);

	printf("%d\n", g_iFree);
	printf("%d\n", g_iAtomic);
	system("pause");

    return 0;
}

DWORD WINAPI ThreadProc1(LPVOID lpThreadParameter)
{
	for (int i = 0; i < 1000000; i++) 
	{ 
		g_iFree++; 
		InterlockedIncrement(&g_iAtomic);
	}

	//g_iFree++;
	//00B032E9 A1 80 91 B0 00       mov         eax, dword ptr ds : [00B09180h]
	//00B032EE 83 C0 01             add         eax, 1
	//00B032F1 A3 80 91 B0 00       mov         dword ptr ds : [00B09180h], eax
	//InterlockedIncrement(&g_iAtomic);
	//00B032F6 F0 FF 05 84 91 B0 00 lock inc    dword ptr ds : [00B09184h]

	return 0;
}

DWORD WINAPI ThreadProc2(LPVOID lpThreadParameter)
{
	for (int i = 0; i < 1000000; i++)
	{
		g_iFree++; 
		InterlockedIncrement(&g_iAtomic);
	}

	return 0;
}

  

posted @ 2017-07-20 16:34  Spobt  阅读(104)  评论(0编辑  收藏  举报