Skip to content

Commit 656a661

Browse files
committed
✨ feat: add useSynchronized
1 parent 11b43bc commit 656a661

File tree

4 files changed

+53
-1
lines changed

4 files changed

+53
-1
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "usepy"
3-
version = "0.2.8"
3+
version = "0.2.9"
44
description = "usepy"
55
homepage = "https://usepy.code05.com/"
66
authors = ["miclon <jcnd@163.com>"]

src/usepy/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
"useAdDict",
1010
"useBloomFilter",
1111
"useCachedProperty",
12+
"useSynchronized",
1213
"useCatchError",
1314
"useCleanHtml",
1415
"useCounter",

src/usepy/core/useSynchronized.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import functools
2+
from threading import Lock
3+
4+
5+
def useSynchronized(func):
6+
"""
7+
线程安全装饰器
8+
>>> @useSynchronized
9+
>>> def demo(x):
10+
>>> return x
11+
"""
12+
@functools.wraps(func)
13+
def wrapper(*args, **kwargs):
14+
lock = vars(func).get("_synchronized_lock", None)
15+
if lock is None:
16+
lock = vars(func).setdefault("_synchronized_lock", Lock())
17+
with lock:
18+
return func(*args, **kwargs)
19+
20+
return wrapper
21+
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import pytest
2+
from usepy import useSynchronized
3+
import threading
4+
5+
6+
@useSynchronized
7+
def add(x, y):
8+
return x + y
9+
10+
11+
def test_useSynchronized_decorator():
12+
13+
def thread_function(result_list):
14+
result = add(1, 2)
15+
result_list.append(result)
16+
17+
results = []
18+
threads = []
19+
num_threads = 10
20+
21+
for _ in range(num_threads):
22+
thread = threading.Thread(target=thread_function, args=(results,))
23+
threads.append(thread)
24+
thread.start()
25+
26+
for thread in threads:
27+
thread.join()
28+
29+
assert all(result == 3 for result in results)
30+

0 commit comments

Comments
 (0)