|
1 | | -import fcntl |
2 | 1 | import threading |
3 | 2 | import time |
| 3 | +import json |
4 | 4 |
|
5 | 5 |
|
6 | | -def writetoTxt(txtFile): |
| 6 | +def writetoTxt(txtFile, mutex, json_file): |
7 | 7 | id = threading.currentThread().getName() |
8 | | - with open(txtFile, 'a') as f: |
9 | | - fcntl.flock(f.fileno(), fcntl.LOCK_EX) # 加锁 |
10 | | - print("{0} acquire lock".format(id)) |
11 | | - f.write("write from {0} \r\n".format(id)) |
12 | | - fcntl.flock(f.fileno(), fcntl.LOCK_UN) # release |
13 | | - time.sleep(3) |
14 | | - |
15 | | - |
16 | | -# 在with块外,文件关闭,自动解锁 |
17 | | -print("{0} exit".format(id)) |
18 | | -for i in range(5): |
19 | | - myThread = threading.Thread(target=writetoTxt, args=("test.txt",)) |
20 | | - myThread.start() |
| 8 | + mutex.acquire(10) |
| 9 | + print("Thread {0} acquire lock".format(id)) |
| 10 | + data = load_json(json_file) |
| 11 | + print('data', data, type(data)) |
| 12 | + time.sleep(1.5) |
| 13 | + print('start add new data') |
| 14 | + |
| 15 | + data.update({id: {"username": str(id), "sex": 'man'}}) |
| 16 | + save_json(data, json_file) |
| 17 | + print('new data', data, type(data)) |
| 18 | + time.sleep(1.5) |
| 19 | + mutex.release() |
| 20 | + print("Thread {0} exit".format(id)) |
| 21 | + |
| 22 | + |
| 23 | +def load_json(json_file): |
| 24 | + with open(json_file, 'r') as f: |
| 25 | + data = json.load(f) |
| 26 | + return data |
| 27 | + |
| 28 | + |
| 29 | +def save_json(data, json_file): |
| 30 | + with open(json_file, 'w') as f: |
| 31 | + json.dump(data, f, indent=4) |
| 32 | + |
| 33 | + |
| 34 | +if __name__ == '__main__': |
| 35 | + a = { |
| 36 | + "lili": {"username": "lili_01", "sex": "woman", "age": 12, "address": "beijing,china."}, |
| 37 | + "lucy": {"username": "lucy_1", "sex": "woman", "age": 32} |
| 38 | + } |
| 39 | + json_file = "a.json" |
| 40 | + save_json(a, json_file) |
| 41 | + |
| 42 | + mutex = threading.Lock() |
| 43 | + for i in range(5): |
| 44 | + myThread = threading.Thread(target=writetoTxt, args=("test.txt", mutex, json_file)) |
| 45 | + myThread.start() |
0 commit comments