메인 스레드없이 다른 모든 pthread를 멈출 수있는 프로그램을 작성하고 싶습니다. pthread_kill
을 사용하여 신호 처리기를 호출하여 블럭을 호출 할 수 있습니다 그 자체. 그러나 나는 붙어있어. 여기에 코드 아래의 (?이 사실이다)Pthread는 블럭 안의 pthread_cond_wait를 사용하여 블럭을 닫습니다.
#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
을 만들 필요가 정말 없다 생각 ... 나는 리눅스 프로그래밍에 초보자입니다. 이 문제를 어떻게 해결할 수 있습니까? 고맙습니다.
이것은 깨졌습니다. 신호 처리기에서 차단해서는 안됩니다! –