file_lock.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import fcntl
  2. import json
  3. import multiprocessing as mp
  4. import time
  5. test_dict = {
  6. "test1": {
  7. "1001": {
  8. "files": "6"
  9. }
  10. },
  11. "test2": {
  12. "2000": {
  13. "files": "0"
  14. },
  15. "2001": {
  16. "files": "1"
  17. }
  18. }
  19. }
  20. def test1(json_path):
  21. with open(json_path, 'a') as test_file:
  22. fcntl.flock(test_file.fileno(), fcntl.LOCK_EX) # 加锁,with块外自动释放锁
  23. json_content = test_dict
  24. # time.sleep(5)
  25. test_file.truncate() # 手动清空
  26. json.dump(json_content, test_file, sort_keys=True, indent=4, separators=(',', ': '))
  27. def test2(json_path):
  28. with open(json_path, 'a') as test_file:
  29. fcntl.flock(test_file.fileno(), fcntl.LOCK_EX)
  30. test_dict['test1'][str(3001)] = {"files": str(7)}
  31. json_content = test_dict
  32. test_file.truncate()
  33. json.dump(json_content, test_file, sort_keys=True, indent=4, separators=(',', ': '))
  34. def init():
  35. with open("file_lock", 'wb') as f:
  36. fcntl.flock(f.fileno(), fcntl.LOCK_EX)
  37. # your init code
  38. if __name__ == '__main__':
  39. json_path = r'./test.json'
  40. p = mp.Process(target=test1, args=(json_path,))
  41. q = mp.Process(target=test2, args=(json_path,))
  42. p.start()
  43. q.start()
  44. p.join()
  45. q.join()