0

When I am giving a sleep of 1 second then i am getting a usual exit but when i comment out sleep(1) and compile and run the program i get getting killed why is that ? I know giving sleep is not the right way ,i want to know how to deal a scenario where we have to call pthread kill and make sure thread exit normally | in a nutshell i want that atleast thread is created and running when pthread_kill is called

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
void *mythread(void *vargp)
{

        printf("Printing from Thread \n");
//      ...
        ...
        printf("End of thread\n");
}


int main()

{
        pthread_t thread_id;
        printf("main start\n");
        pthread_create(&thread_id, NULL, mythread, NULL);
        sleep(1); // <----------- Here
        pthread_kill(thread_id,SIGVTALRM);
}
Learner09
  • 9
  • 1
  • 5
  • With the sleep, the thread you're trying to send a signal to probably no longer exists by that point. Always check for errors from functions that report them. – Shawn Jul 21 '21 at 17:25
  • 3
    Any objective here? I'm not quite sure what you're asking. Using [`pthread_kill`](https://man7.org/linux/man-pages/man3/pthread_kill.3.html) is an "extreme" measure. If you find yourself needing to do this, I suggest rethinking your architecture such that your threads perform their work and exit gracefully, including early exit scenarios. Building on the comment above, the man page says _... an attempt to use a thread ID whose lifetime has ended produces undefined behavior..._, so presumably your thread finishes execution before 1 second, and trying to kill it after that invokes UB. – yano Jul 21 '21 at 17:28
  • 3
    Using signal 9, aka SIGKILL, means that there is no chance for anything in the program as a whole (not just the signalled thread) to respond. A process dies when it is sent SIGKILL. Don't use SIGKILL unless you mean it to be unhandlable. – Jonathan Leffler Jul 21 '21 at 19:30
  • 'I suggest rethinking your architecture such that your threads perform their work and never exit until the entire process terminates and the OS kills all the threads. – Martin James Jul 22 '21 at 00:35
  • how to give enough time so that the thread is created and start running . sleep is not solution how you give time so that atleast first line of thread get start running @MartinJames – Learner09 Jul 22 '21 at 04:06
  • @Shawn In my source code I call pthread create then after some line of code i call pthread kill , the issue is control reaches to pthread_kill before the first line of thread is executed .my question how to make sure atleast thread become up and running when pthread_kill is called – Learner09 Jul 22 '21 at 04:51

0 Answers0