-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
53 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
|