Skip to content

Commit

Permalink
✨ feat: add useSynchronized
Browse files Browse the repository at this point in the history
  • Loading branch information
mic1on committed Jan 22, 2024
1 parent 11b43bc commit 656a661
Show file tree
Hide file tree
Showing 4 changed files with 53 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "usepy"
version = "0.2.8"
version = "0.2.9"
description = "usepy"
homepage = "https://usepy.code05.com/"
authors = ["miclon <jcnd@163.com>"]
Expand Down
1 change: 1 addition & 0 deletions src/usepy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"useAdDict",
"useBloomFilter",
"useCachedProperty",
"useSynchronized",
"useCatchError",
"useCleanHtml",
"useCounter",
Expand Down
21 changes: 21 additions & 0 deletions src/usepy/core/useSynchronized.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import functools
from threading import Lock


def useSynchronized(func):
"""
线程安全装饰器
>>> @useSynchronized
>>> def demo(x):
>>> return x
"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
lock = vars(func).get("_synchronized_lock", None)
if lock is None:
lock = vars(func).setdefault("_synchronized_lock", Lock())
with lock:
return func(*args, **kwargs)

return wrapper

30 changes: 30 additions & 0 deletions tests/test_core/test_useSynchronized.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import pytest
from usepy import useSynchronized
import threading


@useSynchronized
def add(x, y):
return x + y


def test_useSynchronized_decorator():

def thread_function(result_list):
result = add(1, 2)
result_list.append(result)

results = []
threads = []
num_threads = 10

for _ in range(num_threads):
thread = threading.Thread(target=thread_function, args=(results,))
threads.append(thread)
thread.start()

for thread in threads:
thread.join()

assert all(result == 3 for result in results)

0 comments on commit 656a661

Please sign in to comment.