我在课堂作业上遇到了很多麻烦,任何帮助都会很棒。我需要这个代码来创建4个生产者线程,这些线程不断循环并将SIGUSR1或SIGUSR2发送到4个消费者线程。 2只响应SIGUSR1,2只响应SIGUSR2。信号由生产者发送,并由消费者接收,但之后没有任何事情发生,程序崩溃。下面是程序,以及运行时GDB的输出。
DOWN
和gdb
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
#include <signal.h>
#include <time.h>
#define NP 4
#define NC1 2
#define NC2 2
#define CNT 10
void handler1(int);
void handler2(int);
typedef struct {
int sent;
int received;
int buf[1];
int SIG1;
int SIG2;
sem_t con;
sem_t prod;
} sbuf_t;
sbuf_t buff;
pthread_t threads[9];
void *producer() {
srand(time(0));
int s,i;
while(1){
sem_wait(&buff.prod);
s=(rand()%2)+1;
//printf("prod ready \n");
if(s==1){
buff.sent++;
for(i=0;i<4;i++){
pthread_kill(threads[i],SIGUSR1);}
}
else if(s==2){
buff.sent++;
for(i=0;i<4;i++){
pthread_kill(threads[i],SIGUSR1);}
}
usleep(rand()%100000);
sem_post(&buff.prod);
}
}
void *consumer1() {
signal(SIGUSR1, handler1);
//printf("waiting 1\n");
while(1){
}
}
void *consumer2() {
signal(SIGUSR2, handler2);
//printf("waiting 2\n");
while(1){
}
}
void handler1(int signum){
printf("Caught 1\n");
if(signum==SIGUSR1){
sem_wait(&buff.con);
buff.received++;
buff.SIG1++;
sem_post(&buff.con);
}
}
void handler2(int signum){
printf("caught 2 \n");
if(signum==SIGUSR2){
sem_wait(&buff.con);
buff.received++;
buff.SIG2++;
sem_post(&buff.con);
}
}
void main(){
buff.SIG1=0;
buff.SIG2=0;
buff.sent=0;
buff.received=0;
int index;
sem_init(&buff.con, 0, 1);
sem_init(&buff.prod, 0, 1);
for (index = 0;index < NC1;index++) {
pthread_create(&threads[index], NULL, consumer1,NULL);
}
for (index = 0;index < NC2;index++) {
pthread_create(&threads[index+2], NULL, consumer2,NULL);
}
for (index = 0; index < NP; index++) {
pthread_create(&threads[index+4], NULL, producer,NULL);
}
答案 0 :(得分:0)
看看:sigemptyset,sigaddset也许它会帮助你