[Win32]临界区

一、线程安全问题(不是全局、只读)

每个线程都是自己的栈,而局部变量是存储在栈中的,每个线程都有一份自己的局部变量,如果线程仅仅使用局部变量,全那么就不存在线程安全的问题,全局变量不是存储在堆栈中,而存在于全局区这意味着两个线程执行的代码如果访问的是全局变量,那就用的将是同一份全局变量,如果全是读不更改情况也不存在线程安全问题。

// my6.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "windows.h"
#include  "stdlib.h"
int g_dwTickets = 10;

DWORD WINAPI MyFirstThreadPoc(LPVOID lpParameter){

	while (g_dwTickets > 0)
	{
		printf("还有多少票%d \n", g_dwTickets);
		g_dwTickets--;
		printf("卖出一张还有%d \n", g_dwTickets);
	}
	return 0;


}

int main(int argc, char* argv[])
{
	DWORD dwResult1;
	DWORD dwResult2;
	HANDLE aThreadHandles[2];
    //创建线程 aThreadHandles[0] = CreateThread(NULL,0, MyFirstThreadPoc, NULL, 0, NULL);
    //创建新的线程 aThreadHandles[1] = CreateThread(NULL,0, MyFirstThreadPoc, NULL, 0, NULL);     //等线程结束 WaitForMultipleObjects(2, aThreadHandles, true, INFINITE);     //线程执行完了 GetExitCodeThread(aThreadHandles[0], &dwResult1); GetExitCodeThread(aThreadHandles[1], &dwResult2); printf("%d %d", dwResult1, dwResult2); system("pause"); return 0; }

  

二、解决线程安全问题

临界资源:一次只允许一个线程使用的资源叫做临界资源

临界区:访问临界资源的程序是临界区

三、临界区实现线程锁

<1>创建全局变量 CRITICAL_SECTION cs;

<2>初始化全局变量 lnitializeCriticalSection(&cs);

<3>实现临界区

EnterCriticalSection(&cs);  //构建临界区

LeaveCriticalSection(&cs);  //离开临界区

猜你喜欢

转载自www.cnblogs.com/websecyw/p/12976856.html
今日推荐