标签:
线程锁的概念函数EnterCriticalSection和LeaveCriticalSection的使用方法
注:使用结构CRITICAL_SECTION 需增加头文件#include “afxmt.h”
定义一个全局的锁 CRITICAL_SECTION的实例
和一个静态全局变量
创建两个线程函数,代码实现例如以下:
在主函数加入下面代码
输出:
n_AddValue in FirstThread is 1
n_AddValue in FirstThread is 2
n_AddValue in FirstThread is 3
n_AddValue in FirstThread is 4
n_AddValue in FirstThread is 5
n_AddValue in FirstThread is 6
n_AddValue in FirstThread is 7
n_AddValue in FirstThread is 8
n_AddValue in FirstThread is 9
n_AddValue in FirstThread is 10
n_AddValue in SecondThread is 11
n_AddValue in SecondThread is 12
n_AddValue in SecondThread is 13
n_AddValue in SecondThread is 14
n_AddValue in SecondThread is 15
n_AddValue in SecondThread is 16
n_AddValue in SecondThread is 17
n_AddValue in SecondThread is 18
n_AddValue in SecondThread is 19
n_AddValue in SecondThread is 20
假设把两个线程函数中的EnterCriticalSection和LeaveCriticalSection位置移到for循环中去,线程的运行顺序将会改变
输出也就跟着改变,如:
其它代码不变,输出的结果例如以下:
n_AddValue in FirstThread is 1
n_AddValue in SecondThread is 2
n_AddValue in FirstThread is 3
n_AddValue in SecondThread is 4
n_AddValue in FirstThread is 5
n_AddValue in SecondThread is 6
n_AddValue in FirstThread is 7
n_AddValue in SecondThread is 8
n_AddValue in FirstThread is 9
n_AddValue in SecondThread is 10
n_AddValue in FirstThread is 11
n_AddValue in SecondThread is 12
n_AddValue in FirstThread is 13
n_AddValue in SecondThread is 14
n_AddValue in FirstThread is 15
n_AddValue in SecondThread is 16
n_AddValue in FirstThread is 17
n_AddValue in SecondThread is 18
n_AddValue in FirstThread is 19
n_AddValue in SecondThread is 20
个人觉得在函数EnterCriticalSection和LeaveCriticalSection中间的代码运行过程不会被其它线程干拢或者这么讲不同意其它线程中
的代码运行。这样能够有效防止一个全局变量在两个线程中同一时候被操作的可能性
线程锁的概念函数EnterCriticalSection和LeaveCriticalSection的使用方法
标签:
原文地址:http://www.cnblogs.com/gcczhongduan/p/4354210.html