#c #multithreading #producer-consumer
#c #многопоточность #производитель-потребитель
Вопрос:
Я пытаюсь написать многопоточную программу, которая разделяет очередь между производителями и потребителями. Я включил объявления в свой заголовочный файл для структуры, которую я намерен передать в pthread_create (в конечном итоге содержащей аргументы строки cmd), мою общую структуру очереди и прототипы моих функций.
Я попытался прокомментировать практически все в моей основной функции, чтобы посмотреть, смогу ли я заставить свой код хотя бы что-то напечатать, но это не сработало. Заранее извините за длинный пост.
Ниже я включаю свои файлы .h и .c.
multilookup.h
#ifndef MULTILOOKUP_H_
#define MULTILOOKUP_H_
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include "/home/user/Desktop/PA3/util.c"
#define MAX_REQUESTER_THREADS 10
#define MAX_RESOLVER_THREADS 5
#define MAX_INPUT_FILES 10
#define MAXSIZE 20
struct arguments {
struct queue *q;
char *input;
char *resLog;
char *reqLog;
char line[100];
char result[100];
char ipv6[100];
};
struct node {
char name[100];
struct node *next;
};
struct queue {
int size;
struct node *head;
struct node *tail;
};
void init(struct queue *);
void pop(struct queue *);
void push(struct queue *, char *);
void* requesterThread(void *);
//void* resolverThread(queue *, char *, char *, char*);
#endif
multi-lookup.c
#include "multilookup.h"
/*----------------------Struct Functions------------------------*/
void init(struct queue *q) {
q->head = NULL;
q->tail = NULL;
q->size = 0;
}
/* pop: remove and return first name from a queue */
void pop(struct queue *q)
{
q->size--;
//printf("%sn", q->head->name);
struct node *tmp = q->head;
q->head = q->head->next;
free(tmp);
//pthread_exit(NULL);
}
/* push: add name to the end of the queue */
void push(struct queue *q, char *name)
{
q->size ;
if (q->head == NULL) {
q->head = (struct node *)malloc(sizeof(struct node));
//q->head->name = name;
strcpy(q->head->name, name);
q->head->next == NULL;
q->tail = q->head;
} else {
q->tail->next = (struct node *)malloc(sizeof(struct node));
//q->tail->next->name = name;
strcpy(q->tail->next->name, name);
q->tail->next->next = NULL;
q->tail = q->tail->next;
}
//pthread_exit(NULL);
}
/*--------------------------End of struct functions------------------*/
void* requesterThread(void *receivedStruct) {
struct arguments *args_ptr;
args_ptr = (struct arguments*) receivedStruct;
FILE *fptr;
FILE *sptr;
int *fileCounter = 0;
printf("%sn", args_ptr->input);
//Check for proper file paths
if ((fptr = fopen(args_ptr->input, "r")) == NULL) {
fprintf(stderr, "Error! Bogus input file path.n");
// Thread exits if file pointer returns NULL.
exit(1);
}
if ((sptr = fopen(args_ptr->reqLog, "w")) == NULL) {
fprintf(stderr, "Error! Bogues output path.n");
exit(1);
}
//Read from input file and push to shared queue
printf("Adding to Queue...n");
while (fscanf(fptr,"%[^n]%*c", args_ptr->line) != EOF) {
while (args_ptr->q->size == MAXSIZE) {
printf("Queue is full!n");
//block all threads trying to write to shared queue
return 0; //remove later and replace with break;
}
push(args_ptr->q, args_ptr->line);
//Update requesterLog and print logged hostnames
fprintf(sptr, "%s, n", args_ptr->line);
printf("Hostname Logged: %sn", args_ptr->line);
/*LINE TO WRITE "Thread <id> serviced ## files" TO serviced.txt
fprintf(sptr, "Thread %d serviced %d files", pthread_self(), fileCounter);
*/
} fileCounter ; //when fileCounter == numInputFiles send poison pill in queue to let resolver know that the requesterThreads have finished.
fclose(fptr);
pthread_exit(NULL);
return 0;
}
int main(/*int argc, char *argv[]*/) {
printf("1");
int num_req_threads;
int num_res_threads;
int rc1;
int rc2;
//instance of shared queue struct
struct queue *q;
init(q);
printf("2");
//instance of arguments struct
struct arguments args;
args.q = q;
args.input = "/home/user/Desktop/PA3/input/names1.txt";//argv[5];
args.reqLog = "/home/user/Desktop/PA3/serviced.txt";//argv[3];
args.resLog = "/home/user/Desktop/PA3/results.txt"; //argv[4];
return 0;
}
Комментарии:
1. Продолжайте работать над созданием минимального, но воспроизводимого примера. Я вижу include (util.c) без отображаемого кода.
2. Ваши
printf
вызовы буферизуются , поэтому могут быть записаны не тогда, когда вы ожидаете. Пожалуйста, узнайте, как использовать отладчик для обнаружения сбоев.3. Проверьте, что передается
init
и как функция его использует. То есть подумайте, что такое значениеq
. И отладчик был бы отличным инструментом прямо сейчас — сэкономит вам много времени.4. Добавьте новую строку в конце всех вызовов printf. Если вывод осуществляется на терминал, это приведет к очистке буфера.
5. Подсказка: неинициализированные локальные переменные действительно неинициализированы. Теперь подумайте о том, куда указывает указатель
q
вmain
функции…
Ответ №1:
Когда вы пишете:
struct queue *q;
init(q);
не создается структура типа queue
, только указатель, который указывает на ничто. Вы должны попробовать:
struct queue q;
init(amp;q);
так что структура создается до того, как вы попытаетесь назначить ее членам.
Комментарии:
1. Спасибо! Это имеет большой смысл.
2. @Bach если этот ответ вам помог, пожалуйста, примите его!