-1
#include <pthread.h>
#include <stdio.h>

#include <stdlib.h>
#define NUM_THREADS     5


void *PrintHello(void *threadid)
{
    long tid;
    tid = (long)threadid;
    printf("Hello World! It's me, thread #%ld!\n", tid);
    pthread_exit(NULL);
}

int main (int argc, char *argv[])//main
{

    int rc;
    long t;
    for(t=0; t<NUM_THREADS; t++){
        pthread_mutex_lock(&lock);
        printf("In main: creating thread %ld\n", t);
        rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);//creating thread

        if (rc){
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }

    /* Last thing that main() should do */
    pthread_exit(NULL);

}

how to kill remaining all threads when one is release

alk
  • 69,737
  • 10
  • 105
  • 255
DevOpsGeek
  • 302
  • 1
  • 4
  • 15
  • 1
    If you just want to kill everything i.e. terminate the program, use _exit. Note that this does not go through any procedures to release shared resources: it just kills your process. – cup Nov 22 '14 at 08:06
  • Also related: http://stackoverflow.com/q/3822674/694576 And if you want to use the hammer: http://stackoverflow.com/q/2084830/694576 – alk Nov 22 '14 at 11:57

3 Answers3

2

It is bad design to kill another thread. Standard design is to use a variable to indicate to the thread that it should finish. Each thread should check the variable at suitable points in the code and exit accordingly.

The reason is that only the thread knows when it is a good time to exit and it then can clean up after it self.

Karl
  • 170
  • 9
0

Implement a two lock solution. Psuedo code:

void *PrintHello() {
  wait_for(lock1);
  if( test_and_set(lock2) == true) {
     release_others();
     /* Do my stuffstuff... */
  } else {
    /* I'm not first. Exit. */
    pthread_exit(null);
  }
}
Karl
  • 170
  • 9
0

If you aren't bothered about bad design of your code I suggest you try pthread_cancel(thread[t]) to cancel the required thread. (refer http://man7.org/linux/man-pages/man3/pthread_cancel.3.html). I think this is a safe way to do it. Ensure you set the cancel state of your thread.

There's another way in which signals can be raised using pthread_kill(thread[t],SIGKILL) (refer: http://man7.org/linux/man-pages/man3/pthread_kill.3.html). This signal SIGKILL will kill your entire process. You can also raise some other signal instead of SIGKILL in case you want to kill selective thread (refer- https://en.wikipedia.org/wiki/Unix_signal#POSIX_signals) in this case you have to use a signal-handler in the thread (refer-[sigaction][1] or [signal][2]) to handle the signal you are trying to raise and handle it appropriately. But note this method is rather complicated as you will have to block signals in threads you don't want to kill.

Vikram
  • 376
  • 1
  • 12