demoMXSToken.py

demoMXSToken.py
1 import pymxs
2 import threading
3 import time
4 
5 flag = True
6 counter = 0
7 
8 def callMXSEntry():
9  with pymxs.mxstoken():
10  pymxs.runtime.Teapot()
11 
12 # Ex1 and Ex2 used to mark cooperator of mxstoken
13 # when pymxs.mxstoken is gained
14 # python codes are concurrence, but with pymxs.mxstoken blocks are not
15 #
16 def callMXSEntryEx1(locker, tick, evt):
17  global flag, counter
18 
19  try:
20  locker.acquire()
21  flag = False
22  with pymxs.mxstoken():
23  pymxs.runtime.Teapot(Name="callMXSEntryEx1")
24  # give up lock, let Ex2 could exec codes
25  locker.release()
26  if not evt.wait(tick):
27  pymxs.print_("Error: event untiggered\nwhich indicates 'with block' in Ex2 haven't finished\n", True, True)
28  counter = 30
29  except:
30  pymxs.print_("Error: unexpected exception\n", True, True)
31  raise
32  finally:
33  if locker.locked():
34  locker.release()
35 
36 def callMXSEntryEx2(locker, tick, evt):
37  global flag, counter
38  while flag:
39  time.sleep(tick)
40 
41  try:
42  locker.acquire()
43  # we expected this block is finished
44  # before Ex1 wakeup from sleep
45  for i in xrange(10):
46  # only a indicator, could just assign counter = 10
47  counter = counter + 1
48  evt.set()
49  with pymxs.mxstoken():
50  # this block won't be executed after Ex1 with block finished
51  pymxs.runtime.Teapot(Name="callMXSEntryEx2")
52  if counter != 30:
53  pymxs.print_("Error: expected counter 30, got %d\nwhich indicates 'with block' in Ex2 haven't finished\n" % counter, True, True)
54  except:
55  raise
56  finally:
57  if locker.locked():
58  locker.release()
59  pymxs.print_("succss", False, True)
60 
61 def main():
62  locker = threading.Lock()
63  evt = threading.Event()
64  t1 = threading.Thread(target=callMXSEntry)
65  t2 = threading.Thread(target=callMXSEntryEx1, args=(locker, 1, evt))
66  t3 = threading.Thread(target=callMXSEntryEx2, args=(locker, 0.01, evt))
67  t1.start()
68  t2.start()
69  t3.start()
70 
71 if __name__ == "__main__":
72  main()