Home > OS >  C killing child thread stops execution of the main thread
C killing child thread stops execution of the main thread

Time:04-09

I am completely confused with timers and how threads (pthread) work in C

Timers arent timers but clocks and you cant (I at least cant) kill a thread without killing main thread.

What I need - a bit of code which executes once in 24hrs on a separate thread.

However if the app needs to stop it - I cant do anything but send SIGKILL to it (because join will wait till midnight). Once I kill that thread the app (main thread) seems to kill itself also.

I am open to suggestions.

On condition - I cannot use std::threads and I dont want to wake this thread more than once a day

But easiest for me would be to kill a child thread without stopping execution of the main thread (why this is the case anyway??)

Here is the sample:

#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <thread>
#include <pthread.h>
#include <signal.h>

using namespace std;

void* Logger(void* arg) {

    int* thread_state = (int*)arg;

    cout << "Logger started" << endl;

    sleep(24 * 60 * 60);

    cout << "Logger thread exiting" << endl;

    pthread_exit(0);
}

int main()
{
    int thread_state = 0;
    pthread_t logger_t;

    int rc = pthread_create(&logger_t, NULL, Logger, (void*)&thread_state);

    sleep(2);

    //thread_state = 1;
    pthread_kill(logger_t, SIGKILL);

    cout << "i wuz here" << endl;

    return 0;
}

output:

Logger started
Killed

CodePudding user response:

I dont know how I missed it but if I call pthread_cancel instead of pthread_kill it works just fine.

  • Related