|
| 1 | +import threading |
| 2 | +import time |
| 3 | +import json |
| 4 | + |
| 5 | + |
| 6 | +def writetoTxt(txtFile, mutex, json_file): |
| 7 | + id = threading.currentThread().getName() |
| 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