Skip to content

Commit

Permalink
Add check to determine if current thread is main
Browse files Browse the repository at this point in the history
This commit introduces a check to determine if the current
running thread is the main thread. If True, then we continue to block
interactive mode on macOS (it is not possible to share the main thread
with GUI event loop needed for the ImageJ GUI). If False, then the
current thread is *not* the main thread (e.g. a jaunched session) and
interactive mode for macOS can proceed.
  • Loading branch information
elevans committed Jul 12, 2024
1 parent 70c8182 commit a833767
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion src/imagej/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
import sys
import threading
import time
from ctypes import cdll
from enum import Enum
from functools import lru_cache
from pathlib import Path
Expand Down Expand Up @@ -1206,7 +1207,11 @@ def init(
macos = sys.platform == "darwin"

if macos and mode == Mode.INTERACTIVE:
raise EnvironmentError("Sorry, the interactive mode is not available on macOS.")
# check for main thread only on macOS
if _macos_is_main_thread():
raise EnvironmentError(

Check warning on line 1212 in src/imagej/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/imagej/__init__.py#L1211-L1212

Added lines #L1211 - L1212 were not covered by tests
"Sorry, the interactive mode is not available on macOS."
)

if not sj.jvm_started():
success = _create_jvm(ij_dir_or_version_or_endpoint, mode, add_legacy)
Expand Down Expand Up @@ -1517,6 +1522,24 @@ def _includes_imagej_legacy(items: list):
return any(item.startswith("net.imagej:imagej-legacy") for item in items)


def _macos_is_main_thread():
"""Detect if the current thread is the main thread on macOS.
:return: Boolean indicating if the current thread is the main thread.
"""
# try to load the pthread library
try:
pthread = cdll.LoadLibrary("libpthread.dylib")
except OSError as e:
print("No pthread library found.", e)

Check warning on line 1534 in src/imagej/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/imagej/__init__.py#L1531-L1534

Added lines #L1531 - L1534 were not covered by tests

# detect if main thread
if pthread.pthread_main_np() == 1:
return True

Check warning on line 1538 in src/imagej/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/imagej/__init__.py#L1537-L1538

Added lines #L1537 - L1538 were not covered by tests
else:
return False

Check warning on line 1540 in src/imagej/__init__.py

View check run for this annotation

Codecov / codecov/patch

src/imagej/__init__.py#L1540

Added line #L1540 was not covered by tests


def _set_ij_env(ij_dir):
"""
Create a list of required jars and add to the java classpath.
Expand Down

0 comments on commit a833767

Please sign in to comment.