|
@@ -0,0 +1,54 @@
|
|
|
+import fcntl
|
|
|
+import json
|
|
|
+import multiprocessing as mp
|
|
|
+import time
|
|
|
+
|
|
|
+test_dict = {
|
|
|
+ "test1": {
|
|
|
+ "1001": {
|
|
|
+ "files": "6"
|
|
|
+ }
|
|
|
+ },
|
|
|
+ "test2": {
|
|
|
+ "2000": {
|
|
|
+ "files": "0"
|
|
|
+ },
|
|
|
+ "2001": {
|
|
|
+ "files": "1"
|
|
|
+ }
|
|
|
+ }
|
|
|
+}
|
|
|
+
|
|
|
+
|
|
|
+def test1(json_path):
|
|
|
+ with open(json_path, 'a') as test_file:
|
|
|
+ fcntl.flock(test_file.fileno(), fcntl.LOCK_EX) # 加锁,with块外自动释放锁
|
|
|
+ json_content = test_dict
|
|
|
+ # time.sleep(5)
|
|
|
+ test_file.truncate() # 手动清空
|
|
|
+ json.dump(json_content, test_file, sort_keys=True, indent=4, separators=(',', ': '))
|
|
|
+
|
|
|
+
|
|
|
+def test2(json_path):
|
|
|
+ with open(json_path, 'a') as test_file:
|
|
|
+ fcntl.flock(test_file.fileno(), fcntl.LOCK_EX)
|
|
|
+ test_dict['test1'][str(3001)] = {"files": str(7)}
|
|
|
+ json_content = test_dict
|
|
|
+ test_file.truncate()
|
|
|
+ json.dump(json_content, test_file, sort_keys=True, indent=4, separators=(',', ': '))
|
|
|
+
|
|
|
+
|
|
|
+def init():
|
|
|
+ with open("file_lock", 'wb') as f:
|
|
|
+ fcntl.flock(f.fileno(), fcntl.LOCK_EX)
|
|
|
+ # your init code
|
|
|
+
|
|
|
+
|
|
|
+if __name__ == '__main__':
|
|
|
+ json_path = r'./test.json'
|
|
|
+ p = mp.Process(target=test1, args=(json_path,))
|
|
|
+ q = mp.Process(target=test2, args=(json_path,))
|
|
|
+ p.start()
|
|
|
+ q.start()
|
|
|
+ p.join()
|
|
|
+ q.join()
|