简体   繁体   中英

C++ killing child thread stops execution of the main thread

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM