簡體   English   中英

在信號句柄內使用pthread_cond_wait的pthread被阻止

[英]Pthread using pthread_cond_wait inside signal handle blocked

我想編寫一個可以在沒有主線程的情況下停止(掛起)所有其他pthread的程序,我使用pthread_kill將信號發送到目標線程以調用其信號處理程序,該信號處理程序可能會阻塞自身。 但是我被卡住了。 這是下面的代碼:

#include <iostream>
#include <signal.h> 
#include <pthread.h>
#include <unistd.h>
#include <cassert>

using namespace std;

pthread_mutex_t _mutex;
pthread_cond_t cond;

void cur_thread_wait(int sig)
{
    cout << pthread_self() << endl;

//  pthread_mutex_lock(&_mutex);
    pthread_cond_wait(&cond, &_mutex);  
//  pthread_mutex_unlock(&_mutex);
}

void signal_all()
{
    pthread_cond_broadcast(&cond);
}

void *print(void *)
{
    pthread_detach(pthread_self());
    for (int i = 0; i < 100; i ++) {
        cout << dec << i << endl;
    }
    return nullptr;
}


int main(int argc, char *argv[]) 
{
    pthread_mutex_init(&_mutex, nullptr);
    pthread_cond_init(&cond, nullptr);

    signal(SIGUSR1, cur_thread_wait);

    pthread_t pid1, pid2, pid3;
    pthread_create(&pid1, nullptr, print, nullptr);
    pthread_create(&pid2, nullptr, print, nullptr);
    pthread_create(&pid3, nullptr, print, nullptr);

//  usleep(400);

    pthread_kill(pid1, SIGUSR1);
    pthread_kill(pid2, SIGUSR1);
    pthread_kill(pid3, SIGUSR1);

    signal_all();


    pthread_exit(nullptr);
}

實際上,我認為確實不需要創建mutex (是嗎?)...我是linux編程的新手。 我該如何解決這個問題? 謝謝。

在調用pthread_cond_wait之前,您確實需要鎖定互斥鎖。 它期望它被鎖定,然后將其解鎖,等待條件變量被斷言,然后在重新返回給您之前重新鎖定它。

來自pthread_cond_wait(3p)

int pthread_cond_wait(pthread_cond_t *restrict cond,
    pthread_mutex_t *restrict mutex);

pthread_cond_timedwait()pthread_cond_wait()函數應在條件變量上阻塞。 應用程序應確保使用調用線程鎖定的互斥鎖來調用這些函數; 否則,將導致錯誤(對於PTHREAD_MUTEX_ERRORCHECK和健壯的互斥鎖)或未定義的行為(對於其他互斥鎖)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM