Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 1.0.6

- PreprocessorExt: add option `multithread`

# 1.0.5

- PreprocessorExt: fixed the definition of `run_in_thread`, which is a decorator for the file processing function.
Expand Down
41 changes: 27 additions & 14 deletions foliant/preprocessors/utils/preprocessor_ext.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,19 +14,30 @@
MAX_THREADS = max(1, os.cpu_count() - 2)
thread_semaphore = threading.Semaphore(MAX_THREADS)

def run_in_thread(fn):
@wraps(fn)
def run(*args, **kwargs):
def wrapper():
try:
fn(*args, **kwargs)
finally:
thread_semaphore.release()

thread_semaphore.acquire()
threading.Thread(target=wrapper, daemon=True).start()
def run_in_thread(enabled=True):
"""
If enabled=False, returns the original function immediately without wrapping.
"""
def actual_decorator(fn):
if not enabled:
return fn

@wraps(fn)
def wrapper(*args, **kwargs):
def thread_task():
try:
fn(*args, **kwargs)
finally:
thread_semaphore.release()

thread_semaphore.acquire()
thread = threading.Thread(target=thread_task, daemon=True)
thread.start()
return thread

return run
return wrapper

return actual_decorator

def allow_fail(msg: str = 'Failed to process tag. Skipping.') -> Callable:
"""
Expand Down Expand Up @@ -159,7 +170,8 @@ def _process_tags_for_all_files(self,
'''
self.logger.info(log_msg)

@run_in_thread
multithread = self.context['config'].get('multithread', False)
@run_in_thread(enabled=multithread)
def process(self, markdown_file_path):
self.current_filepath = Path(markdown_file_path)
self.current_filename = str(self.current_filepath.
Expand Down Expand Up @@ -193,7 +205,8 @@ def _process_all_files(self,
'''Apply function func to all Markdown-files in the working dir'''
self.logger.info(log_msg)

@run_in_thread
multithread = self.context['config'].get('multithread', False)
@run_in_thread(enabled=multithread)
def process(markdown_file_path):
self.current_filepath = Path(markdown_file_path)
self.current_filename = str(self.current_filepath.
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
description=SHORT_DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type='text/markdown',
version='1.0.5',
version='1.0.6',
author='Daniil Minukhin',
author_email='ddddsa@gmail.com',
url='https://github.com/foliant-docs/foliantcontrib.utils',
Expand Down