Source code for rwlock.user

"""
Module **sesf.rwlock.user** has class ``User`` that implements a user of
the read-write-lock service. To drive a rwlock implementation, run

"``python user.py <num_threads> <num_ops> <rwl_imp>``"

where ``<rwl_imp>`` is the implementation module and any command line
arguments (eg, ``imp_0.imp``), to drive the implementation with
``num_threads`` user threads, each issuing ``num_ops`` read or write
(randomly chosen) operations.
"""

# from threading import Thread, Lock, Condition
from threading import Thread, get_ident
import importlib, random, time, sys, argparse

[docs]class User(): def __init__(self, argv): print('starting rwlock.user', argv, flush=True) p = argparse.ArgumentParser( usage='python user.py [-h] num_threads num_ops rwlock', description='create a user to drive the given rwlock implementation') p.add_argument("num_threads", type=int, help='number of user threads') p.add_argument("num_ops", type=int, help='number of read or write operations per thread') p.add_argument("rwlock", nargs=argparse.REMAINDER, help='rwlock implementation module and any args') args = p.parse_args(argv[1:]) print("rwlockuser args:", args) self.num_threads = args.num_threads self.num_ops = args.num_ops self.user_threads = [] self.using_service_imp = False rwlmodule = importlib.import_module(args.rwlock[0]) # if hasattr(rwlmodule, 'Service'): # self.using_service_imp = True # rwl_imp = rwlmodule.Service() # elif len(args.rwlock) == 1: if len(args.rwlock) == 1: rwl_imp = rwlmodule.Imp() else: rwl_imp = rwlmodule.Imp(args.rwlock) print("rwlock", rwl_imp) self.imp = rwl_imp for j in range(self.num_threads): t = Thread(target=self.do_rwops) self.user_threads.append(t) t.start() def do_rwops(self): tid = get_ident() print('starting user thread', tid, 'doing', self.num_ops, 'reads or writes') for k in range(self.num_ops): time.sleep(random.random()*1) # randomly select read or write operation if random.randint(0, 1): self.imp.acqr() print('thread', tid, 'acqr') time.sleep(random.random()*2) print('thread', tid, 'relr') self.imp.relr() else: self.imp.acqw() print('thread', tid, 'acqw') time.sleep(random.random()*1) self.imp.relw() print('thread', tid, 'relw')
if __name__ == '__main__': rwlock_user = User(sys.argv) # if rwlock_user.imp has __end__ (ie, is service_imp), end service process if hasattr(rwlock_user.imp, '__end__'): for t in rwlock_user.user_threads: t.join() rwlock_user.imp.__end__()