THREADKILL Halt execution of a thread

Section: FreeMat Threads


The threadkill function stops (or attempts to stop) execution of the given thread. It works only for functions defined in M-files (i.e., not for built in or imported functions), and it works by setting a flag that causes the thread to stop execution at the next available statement. The syntax for this function is

where handle is the value returned by a threadnew call. Note that the threadkill function returns immediately. It is still your responsibility to call threadfree to free the thread you have halted. You cannot kill the main thread (thread id 1).


Here is an example of stopping a runaway thread using threadkill. Note that the thread function in this case is an M-file function. We start by setting up a free running counter, where we can access the counter from the global variables.

function freecount
  global count
  if (~exist('count')) count = 0; end  % Initialize the counter
  while (1)
    count = count + 1;                 % Update the counter

We now launch this function in a thread, and use threadkill to stop it:

--> a = threadnew;
--> global count                   % register the global variable count
--> count = 0;
--> threadstart(a,'freecount',0)   % start the thread
--> count                          % it is counting

ans = 

--> sleep(1)                       % Wait a bit
--> count                          % it is still counting

ans = 

--> threadkill(a)                  % kill the counter
--> threadwait(a,1000)             % wait for it to finish

ans = 

--> count                          % The count will no longer increase

ans = 

--> sleep(1)
--> count

ans = 

--> threadfree(a)