# How to kill a thread



## www_glgth_com (Dec 16, 2008)

If we want to kill process, we use kill <process num>, but how can I kill the thread by system kill command?

for example, I create 10 threads by pthread_create, every thread runtime has an infinite loop, then I use the FreeBSD system command to kill the threads one by one, How can I do?

thank you.


----------



## graudeejs (Dec 16, 2008)

man kill

signals
     1	     HUP (hang up)
     2	     INT (interrupt)
     3	     QUIT (quit)
     6	     ABRT (abort)
     9	     KILL (non-catchable, non-ignorable kill)
     14      ALRM (alarm clock)
     15      TERM (software termination signal)


----------



## DutchDaemon (Dec 16, 2008)

Kill applies to process ids, not to individual threads belonging to those processes. Check ps -axH or top -H: all threads belong to a single pid and cannot (IMO) be addresses or killed individually.

Example:


```
1236  ??  S      5:02.17 /usr/local/lib/firefox3/firefox-bin
 1236  ??  S      0:01.59 /usr/local/lib/firefox3/firefox-bin
 1236  ??  S      0:11.42 /usr/local/lib/firefox3/firefox-bin
 1236  ??  I      0:00.03 /usr/local/lib/firefox3/firefox-bin
 1236  ??  I      0:00.00 /usr/local/lib/firefox3/firefox-bin
 1236  ??  I      0:02.79 /usr/local/lib/firefox3/firefox-bin
 1236  ??  S      0:00.00 /usr/local/lib/firefox3/firefox-bin
 1236  ??  S      0:00.00 /usr/local/lib/firefox3/firefox-bin
```


```
1236 user    44    0   197M   183M select 1   5:05  0.00% firefox-bin
 1236 user    44    0   197M   183M ucond  0   0:12  0.00% firefox-bin
 1236 user    44    0   197M   183M ucond  0   0:03  0.00% firefox-bin
```


----------



## gordon@ (Dec 17, 2008)

www_glgth_com said:
			
		

> If we want to kill process, we use kill <process num>, but how can I kill the thread by system kill command?
> 
> for example, I create 10 threads by pthread_create, every thread runtime has an infinite loop, then I use the FreeBSD system command to kill the threads one by one, How can I do?
> 
> thank you.



Threads are an integral part of a process and cannot be killed. Imagine you had a process that had 2 threads. One thread wrote via a named pipe to the other (contrived example). If you killed one, it would completely hose the other and make the process hang.

In short, you can't.


----------



## www_glgth_com (Dec 17, 2008)

I see, tks


----------



## fonz (Dec 17, 2008)

Not sure if this is what you want, but from within the process itself you can use pthread_kill() to send signals to individual threads (provided you kept track of the pthread_t objects, e.g. by storing them in an array, linked list or other similar structure).

*As far as I know*, killing a thread from the command line (e.g. from outside the originating process) by LWP ID isn't possible on BSD systems. Linux does allow this, but IMHO that can easily lead to a big mess.

Fonz


----------



## DutchDaemon (Dec 17, 2008)

The difference being (I think) that Linux handles threads in the kernel (which allows more room for manipulation), whereas FreeBSD handles them in user space.


----------



## trasz@ (Dec 17, 2008)

DutchDaemon said:
			
		

> The difference being (I think) that Linux handles threads in the kernel (which allows more room for manipulation), whereas FreeBSD handles them in user space.



No.  FreeBSD uses the same 1:1 threading model.


----------



## DutchDaemon (Dec 17, 2008)

Right you are, of course. never rely on outdated info


----------



## fonz (Dec 17, 2008)

www_glgth_com said:
			
		

> how can I kill the thread by system kill command?



I'm not near a FreeBSD box right now, but maybe you can try using ps -H to find a thread's LWPID (or TID, if you like) and then see if kill accepts that as an argument.

Like I said, I can't try it out right now so I can't say for sure if it will work but it's an idea.

Fonz


----------



## DutchDaemon (Dec 17, 2008)

ps -H gives you nothing you can use. See http://forums.freebsd.org/showpost.php?p=6015&postcount=3


----------



## fonz (Dec 17, 2008)

Noted, thanks.


----------



## Jusctsch (Jun 17, 2011)

I hate to revive slightly old threads, but channeling DutchDaemon I would say that it's worth it to clear up somethings that may be outdated.

Look at the procstat command that can be called via command line, specifically the -t argument.

Given the corresponding PID, we can look at the running threads (actually it will return kernel scheduled lwps that map 1:1 to user threads). These lwp_ids will be unique across the whole system- not just in the running process.

The key is the sysctl function, and this can be pulled into your own code. This is very useful in things like gdb, that need to have knowledge of the current running threads.

These lwpids apparently can be used with things like ptrace (although I haven't had much luck currently) and you can send signals such as SIGSTOP using the kill() command. The light-weight processes *should* be handled just like processes, but I am discovering that this is not always the case. At the very least, you can obtain these lwp_ids and learn how many user-threads the given process has running.

It seems like it's still kind of half-baked at this point and reading materials seem to call these lwps "kernel threads" or "tasks", maybe someone could clarify more. This is using libthr (1:1) and FreeBSD 8.1


----------



## Jusctsch (Jun 17, 2011)

I guess ultimately it will require the equivalent of the lwp_kill or tkill syscall. From lin-lwp.c in FreeBSD 8.1 source/contrib/gdb/gdb:


```
static int
kill_lwp (int lwpid, int signo)
{
  errno = 0;

/* Use tkill, if possible, in case we are using nptl threads.  If tkill
   fails, then we are not using nptl threads and we should be using kill.  */

#ifdef HAVE_TKILL_SYSCALL
  if (!tkill_failed)
    {
      int ret = syscall (__NR_tkill, lwpid, signo);
      if (errno != ENOSYS)
	return ret;
      errno = 0;
      tkill_failed = 1;
    }
#endif


  return kill (lwpid, signo);
```

Info about nptl
http://en.wikipedia.org/wiki/Native_POSIX_Thread_Library

It seems like BSD doesn't have this syscall. BSD supports LinuxThreads, but I don't think there is an equivalent to nptl.


----------



## qsecofr (Jun 17, 2011)

Conceptually speaking, it might be better to design the application such that the child threads know when to end themselves.  The workers themselves can determine when to end maybe by some sort of inactivity threshold.  Also, any threads might want to poll for cancel requests to perform cleanup or releasing of resources gracefully.  And, might not be a bad idea to yield explicitly in the worker thread code at appropriate times.

Infinite loops make me think of all the things that could go wrong that weren't accounted for..

If you need a way to kill off individual threads, then maybe design the application so that the main thread spawns the workers, maintains the pool, and acts on your behalf to kill a thread gracefully.


----------



## fonz (Jun 19, 2011)

*Generally speaking, yes.*



			
				qsecofr said:
			
		

> Conceptually speaking, it might be better to design the application such that the child threads know when to end themselves.
> [snip]
> If you need a way to kill off individual threads, then maybe design the application so that the main thread spawns the workers, maintains the pool, and acts on your behalf to kill a thread gracefully.


That would be a sensible approach indeed, but mind you: it can be quite tricky to get it right. Concurrent and/or distributed programming in general isn't easy. Big books and entire (under)graduate courses can be filled with this topic :beergrin

Fonz


----------



## qsecofr (Jun 20, 2011)

Agreed 100%, the learning curve is steep.  It's usually pretty important to the application as a whole not to let a thread die while holding a resource, as Gordon alluded to.


----------

