给BT:MAKE-THREAD一个htop可见名称(SBCL)

时间:2016-04-19 09:35:52

标签: linux multithreading common-lisp sbcl

Python,通过prctl(https://pypi.python.org/pypi/python-prctl)允许设置一个线程的名称,以便您可以在程序中看到它' htop'。如何在SBCL中做到这一点? BT:MAKE-THREAD没有公开界面,SBCL似乎也没有。函数SB-THREAD :: MAKE-THREAD创建一个在sbcl / src / code / thread.lisp中定义的defstruct,它没有与此afaict相关的代码。)

另请参阅:Python thread name doesn't show up on ps or htop

2 个答案:

答案 0 :(得分:1)

使用old version OSICAT-POSIX进行操作。尝试

(setf (osicat:process-name) "phuctor")

这将设置当前线程名称。

答案 1 :(得分:1)

SBCL bug "thread name visible in htop"与Tomas Hlavaty的proposed solution相关,不需要SBCL补丁:

(defun set-native-thread-name (thread name)
  #+(and sb-thread linux)
  (when (and (stringp name) (not (equal "" name)))
    (let ((n (with-output-to-string (s)
               (dotimes (i (min (length name) 15))
                 (let ((c (char name i)))
                   (if (<= 32 (char-code c) 126)
                       (write-char c s)
                       (return-from set-native-thread-name)))))))
      (with-alien ((fn (function integer unsigned c-string)
                       :extern "pthread_setname_np"))
        (values (alien-funcall fn
                               (sb-thread::thread-os-thread thread)
                               n))))))

(defun update-native-thread-names ()
  #+sb-thread
  (dolist (x (sb-thread:list-all-threads))
    (set-native-thread-name x (sb-thread:thread-name x))))

(defun set-thread-name (name &optional thread)
  #+sb-thread
  (let ((thread (or thread sb-thread:*current-thread*)))
    (setf (sb-thread:thread-name thread) name)
    (set-native-thread-name thread name)))

;; example
(sb-thread:make-thread
 (lambda ()
   (set-thread-name "ahoj")
   (sleep 10)
   ;; see the thread name in htop
   (print :done)
   (finish-output)))