Comment 5 for bug 1399727

Revision history for this message
Tomas Hlavaty (q-tom-o) wrote :

Much better sollution, without changes to sbcl:

- do not use NAME argument when creating threads

- set the thread name at the beginning of THUNK instead

- call UPDATE-NATIVE-THREAD-NAMES to get the effect even for threads not created by the application

application code:

(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)))