Skip to content
This repository was archived by the owner on Mar 8, 2024. It is now read-only.

Commit c7a9f04

Browse files
author
shibing624
committed
deal with write and read file thread.
1 parent e3691e8 commit c7a9f04

3 files changed

Lines changed: 60 additions & 60 deletions

File tree

23thread/file_thread_demo.py

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,45 @@
1-
import fcntl
21
import threading
32
import time
3+
import json
44

55

6-
def writetoTxt(txtFile):
6+
def writetoTxt(txtFile, mutex, json_file):
77
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()

23thread/file_thread_demo2.py

Lines changed: 0 additions & 45 deletions
This file was deleted.

23thread/file_thread_demo_linux.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import fcntl
2+
import threading
3+
import time
4+
5+
6+
def writetoTxt(txtFile):
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()

0 commit comments

Comments
 (0)