Names Default To Here(1);

Open Read Write = Function({filePath},{Default Local},

	attempts = 0;
	maxAttempts = 500;
	delay = 0.1;
	isLocked = 1;   //<-- assume locked to kickstart the while loop
	openError = 0;
	eofError = 0;	
	
	While( (isLocked | openError | eofError) & (attempts<maxAttempts),
	
		attempts++;
		
		// open the table and capture errors that might appear in the log
		openlog = Log Capture( dt = Open(filePath,Invisible) );
				
		// this is a rare error when JMP can't create a 'process'
		openError = Contains(openlog,"Cannot open table");	
		if (openError,
			Wait(delay);
			Continue()
		);
		
		// test save to verify write access
		openlog = Log Capture( dt << save );		
		
		// detect if the file is locked (by another user)
		isLocked = Contains(openlog,"File not open in Write mode") > 0;
		
		// in trouble now
		eofError = Contains(openlog,"Unable to get End of File marker") > 0;

		if (isLocked | eofError,
			Close(dt,nosave);
			Wait(delay)
		);					
	
	);
	
	if (openError | isLocked | eofError,
		show(openError,isLocked,eofError);
		retval = Empty()
	,
		retval = dt
	);

	show(attempts);
	
	Return(retval);		

);

Save And Close = Function({dt},{Default Local},
	
	// we should only be saving a table if we have 
	// read-write access, but in case our locking test
	// failed, do another set of tests so ensure write access
	savelog = Log Capture( dt << save );
	noWriteAccess = Contains(savelog,"File not open in Write mode");
	if (noWriteAccess,
		Write("\!Nunable to save - no write access")
	);
	eofError = Contains(savelog,"Unable to get End of File marker");
	if (eofError,
		Write("\!Ntrying to save - unable to get end of file marker")
	);
	
	// now that we have (tried to) save, close the table
	Close(dt,nosave);
	
);

path = "C:\Users\david\Downloads\results.jmp";

t1 = Tick seconds();
	
for (i=1,i<=50,i++,

	show(i);
	if (!File Exists(path),
		Write("\!N\!NFile not found\!N");
		Break();
	);
	
	dt = Open Read Write(path);

	// skip if we don't have a table
	if (isEmpty(dt),Continue());
	
	// mimic some user-activity
	r = Random Uniform(.5,1.5);
	Wait(r);
	Column(dt,2)[i] = i;
	
	Save And Close(dt);
	
	// allow some idle time between file locks
	Wait(0.05);
	
);

t2 = Tick seconds();
show(t2-t1);
