Skip to content

Instantly share code, notes, and snippets.

@yamule
Last active July 6, 2019 05:52
Show Gist options
  • Save yamule/8e1c8cc5d6769a230efbbede93598042 to your computer and use it in GitHub Desktop.
Save yamule/8e1c8cc5d6769a230efbbede93598042 to your computer and use it in GitHub Desktop.
mimic flock with sqlite
import sqlite3
import time
import random;
import sys;
locker_dbpath = "dummy_locker.db";
locker_tablename = "dummy_table";
locker_conn = None;
#public domain
def get_lock():
global locker_conn;
global locker_tablename;
global locker_dbpath;
try:
locker_conn = sqlite3.connect(locker_dbpath, isolation_level='EXCLUSIVE')
locker_conn.execute("DROP TABLE IF EXISTS "+locker_tablename)
locker_conn.execute("create table "+locker_tablename+" (tid int)")
locker_conn.execute("insert into "+locker_tablename+" values(1)")
except sqlite3.OperationalError :
if not locker_conn == None:
locker_conn.close();
return False;
return True;
def release_lock():
global locker_conn;
if not locker_conn == None:
locker_conn.commit();
locker_conn.close();
#---------- example code --------------
#call this script multiple times.
import os;
processid = str(os.getpid());
for ii in range(100):
lchk = get_lock();
if lchk:
sys.stdout.write(" processing "+processid+" >>>");
sys.stdout.flush();
time.sleep(int(20*random.random()+1));
sys.stdout.write(" finished "+processid+".\n");
release_lock();
time.sleep(5*random.random());
else:
sys.stdout.write("\ntried "+processid+" but db was locked.\n");
time.sleep(5*random.random());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment