我有一个任务,我被卡住了,我不知道问题出在哪里,但是我必须使用一个线程从文件中获取两个数字,在屏幕上打印数字,然后另一个线程将它们两个数字相加,然后将它们打印在屏幕上。这是我到目前为止所拥有的,但我似乎无法让它正常工作,任何帮助将不胜感激。 我应该指出,我必须在不使用互斥锁和信号量的情况下做到这一点。
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
typedef struct
{
int a;
int b;
} pair_t;
FILE *f;
static void * reader(void *data){
pair_t *d = (pair_t *)data;
sigset_t catch;
int flag;
sigemptyset(&catch);
sigaddset(&catch, SIGUSR1);
while(!feof(f)){
sigwait(&catch, &flag);
fscanf(f,"%d", &d->a);
fscanf(f,"%d", &d->b);
printf("Thread 1 submitting : %d %d", d->a, d->b);
sleep(5);
}
return 0;
}
static void * calculator(void *data){
pair_t *pa = (pair_t *)data;
sigset_t catch;
sigemptyset(&catch);
sigaddset(&catch, SIGUSR1);
int flag;
while(1){
sigwait(&catch, &flag);
printf("Thread 2 calculated = %d\n",(pa->a + pa->b));
sleep(5);
}
return 0;
}
int main(int argc, char *argv[]){
f = fopen(argv[1],"r");
if(f ==NULL){
perror;
}
if(f !=NULL){
pair_t * p;
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGUSR1);
pthread_t t1;
pthread_t t2;
pthread_sigmask(SIG_BLOCK, &set, NULL);
pthread_create(&t1, NULL, reader, (void *)&p);
pthread_create(&t2, NULL, calculator, (void *)&p);
pthread_join(t1, NULL);
printf("Goodbye from Thread One");
pthread_join(t2, NULL);
printf("Goodbye from Thread Two");
pthread_exit(NULL);
}
return 0;
}