V
V
Vasily Demin2020-02-18 01:40:57
C++ / C#
Vasily Demin, 2020-02-18 01:40:57

How good is it to use pthread_kill to resume threads?

There are several threads that are created at the beginning of the program and immediately put into standby mode. At any time, you can transfer data to these threads and wake them from sleep mode, while the main program must wait for all threads to complete their work. When a thread has completed its work, it must inform the main program about this and dive into the waiting mode. How good is it to use signals to wake threads from sleep, and should we use condition variables for this?

Explanatory code:

void* worker(void *arg) {
    struct sigset_t *sig = arg;
    int sig_num;
    for(;;) {
        // Ожидание SIGUSR1
        sigwait(sig, &sig_num);

        // Выполнение работы

        // Сигнализируем о выполненной работе
    }
    return NULL;
}

int main() {
    struct sigset_t sig;
    sigemptyset(&sig);
    sigaddset(&sig, SIGUSR1);
    pthread_sigmask(SIG_BLOCK, &sig, NULL);

    // Создаём 4 потока
    pthread_t threads[4];
    for(int i = 0; i < 4; i++) {
        pthread_create(&threads[i], NULL, worker, &sig);
    }

    // Некоторый код
    // Некоторый код
    // Некоторый код

    // Передаём данные через глобальные переменные 4-м потокам

    // Выводим 4-е потока из спящего режима
    for(int i = 0; i < 4; i++) {
        pthread_kill(threads[i], SIGUSR1);
    }

   // Ожидаем выполнения 4-х потоков
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jcmvbkbc, 2020-02-18
@includedlibrary

How good is it to use signals to wake threads from sleep, and is it worth using ...

It is a solution, but not the most traditional one. How good depends on how the threads work together/how the data is shared between them. Not enough context to answer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question