我正在尝试使用 POSIX 线程和信号量来实现生产者/消费者问题,但我面临以下错误:
sema.c: In function ‘initialize_variables’:
sema.c:55:8: error: expected expression before ‘{’ token
我检查了我的代码,但看不到该错误的归属。
这是代码:
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
#define TRUE 1
pthread_mutex_t mutex;
sem_t full, empty;
int buffer[BUFFER_SIZE];
int counter;
void* producer(void*);
void* consumer(void*);
int insert_item(void);
int remove_item(void);
void initialize_variables();
int main(int argc, char *argv[]) {
int number_Pro;
int number_Cons;
int i;
if(argc!=3){
printf("Not enough parameters\n");
exit(0);
}
number_Pro = atoi(argv[1]);
number_Cons = atoi(argv[2]);
pthread_t t_array_Pro[number_Pro];
pthread_t t_array_Cons[number_Cons];
initialize_variables();
for(i=0; i<number_Pro; i++)
pthread_create(&t_array_Pro[i],NULL,producer,NULL);
for(i=0; i<number_Cons; i++)
pthread_create(&t_array_Cons[i],NULL,consumer,NULL);
return 0;
}
void initialize_variables(){
mutex=PTHREAD_MUTEX_INITIALIZER;
sem_init(&full,0,0);
sem_init(&empty,0,BUFFER_SIZE);
counter = 0;
}
void* producer(void* arg){
while(TRUE){
sem_wait(&empty);
phtread_mutex_lock(&mutex);
if(insert_item())
printf("Error in Producer\n");
else
printf("Producer produced a new item\n");
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void* consumer(void* arg){
while(TRUE){
sem_wait(&full);
phtread_mutex_lock(&mutex);
if(remove_item())
printf("Error in Consumer\n");
else
printf("Consumer consumed an item from the buffer\n");
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int insert_item(void){
if(counter < BUFFER_SIZE){
buffer[counter]=1;
counter++;
return 0;
}
else
return -1;
}
int remove_item(void){
if(counter > 0){
buffer[counter]=0;
counter--;
return 0;
}
else
return -1;
}