Option ExplicitDim blTime1 As Boolean Dim bltime2 As BooleanDim Data As LongPrivate Sub Form_Load() blTime1 = True bltime2 = False End SubPrivate Sub Timer1_Timer() If blTime1 Then bltime2 = False Data = Data + 1 bltime2 = True End If Label1.Caption = Data End Sub Private Sub Timer2_Timer() If bltime2 Then blTime1 = False Data = Data - 1 blTime1 = True End If Label2.Caption = Data End Sub
在两个timer中调用如下的操作变量的过程 private sub optVar() static busy as boolean if busy=true then exit sub busy=true'这里操作变量'操作完毕 busy=false end sub
Option ExplicitDim blTime1 As Boolean Dim bltime2 As BooleanDim Data As Long '要访问的变量Private Sub Form_Load() blTime1 = True bltime2 = False End SubPrivate Sub Timer1_Timer() If blTime1 Then '如果Timer1在访问的时候 bltime2 = False '不让Timer2访问 Data = Data + 1 bltime2 = True '访问结束后,再让Timer2访问, End If Label1.Caption = Data End Sub''以下的代码同理. Private Sub Timer2_Timer() If bltime2 Then blTime1 = False Data = Data - 1 blTime1 = True End If Label2.Caption = Data End Sub
似乎不太好,这样两个timer好像就不能同时工作,效率可能就下降了吧
2楼的肯定不行,两个timer是并发的
我想的这个 首先定义 mutex1 as integer mutex1=1 另其初值为1muTag: Mutex1 = Mutex1 - 1 ’请求进入 If mutex < 0 Then '如果目前已被别人占用 Mutex1 = Mutex1 + 1 '释放请求 GoTo muTag ’继续请求 End If '请求成功,访问互斥变量代码 ..... ' Mutex1 = Mutex1 + 1 ‘释放临界资源行吗?
Option ExplicitDim blTime1 As Boolean
Dim bltime2 As BooleanDim Data As LongPrivate Sub Form_Load()
blTime1 = True
bltime2 = False
End SubPrivate Sub Timer1_Timer()
If blTime1 Then
bltime2 = False
Data = Data + 1
bltime2 = True
End If
Label1.Caption = Data
End Sub
Private Sub Timer2_Timer()
If bltime2 Then
blTime1 = False
Data = Data - 1
blTime1 = True
End If
Label2.Caption = Data
End Sub
private sub optVar()
static busy as boolean
if busy=true then exit sub
busy=true'这里操作变量'操作完毕
busy=false
end sub
Option ExplicitDim blTime1 As Boolean
Dim bltime2 As BooleanDim Data As Long '要访问的变量Private Sub Form_Load()
blTime1 = True
bltime2 = False
End SubPrivate Sub Timer1_Timer()
If blTime1 Then '如果Timer1在访问的时候
bltime2 = False '不让Timer2访问
Data = Data + 1
bltime2 = True '访问结束后,再让Timer2访问,
End If
Label1.Caption = Data
End Sub''以下的代码同理.
Private Sub Timer2_Timer()
If bltime2 Then
blTime1 = False
Data = Data - 1
blTime1 = True
End If
Label2.Caption = Data
End Sub
首先定义 mutex1 as integer
mutex1=1 另其初值为1muTag: Mutex1 = Mutex1 - 1 ’请求进入
If mutex < 0 Then '如果目前已被别人占用
Mutex1 = Mutex1 + 1 '释放请求
GoTo muTag ’继续请求
End If '请求成功,访问互斥变量代码
.....
'
Mutex1 = Mutex1 + 1 ‘释放临界资源行吗?
你也可以用循环判断标记变量,一旦一个timer释放了访问,另外一个马上继续执行。
临界资源肯定不能同时访问,但是两个timer并不是每次执行都要访问临界资源,其实仅是当某个条件满足时才去访问临界资源,修改变量。所以,仅让在一个时刻一个timer运行效率我觉得肯定要低。
我觉得两个timer应该是并发执行的,无法控制其执行顺序。
设置一个布尔变量.对于每一个访问资源的过程来说.在确认要访问的时候将 布尔变量 设置 True.(表示此资源有人在访问了.)对于每一个要求访问资源的过程来说,都先判断 布尔变量 是否为True 如果为True 则不让其访问. 对于每一个访问完了资源的过程来说.都要在访问完后,将 布尔变量 设置为 False
再判断队列是否为空.如果 布尔变量 为 Flase 且 队列不为空.则从队列中取出一个任务进行访问资源. 并且重新对队列进行操作(减少一个任务).(你可以先进先出.队列,先可以后进先出.栈)
有可能两个线程同时进行判断都为true,然后同时进入了。
例如
p1先执行: if v=true then,然后p1被挂起,没有机会去修改标志位
p2执行: if v=true then,p2进入临界区
p1继续执行 v=false,已经没有意义了?p1,p2同时进入了临界区