我无法调试以下程序,因为我家里没有 linux。我无法执行该程序,但是当我在实验室会话中编译该程序时,我遇到了两个错误。谁能帮我吗?如果有人在调试后能够执行此程序,请发布输出。
代码如下:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#define BUFFER_SIZE 10
sem_t empty;
sem_t full;
pthread_mutex_t mutex;
int buffer[BUFFER_SIZE];
pthread_t ptid,ctid;
pthread_attr_t attr;
void *producer(void *param);
void *consumer(void *param);
int counter;
int main()
{
init();
pthread_create(&ptid, &attr, producer, NULL);
pthread_create(&ctid, &attr, consumer, NULL);
pthread_join(ptid,NULL);
pthread_join(ctid,NULL);
return 0;
}
void init()
{
pthread_mutex_init(&mutex, NULL);
pthread_attr_init(&attr);
sem_init(&full, 0, 0);
sem_init(&empty, 0, BUFFER_SIZE);
counter = 0;
for(int j=0;j<BUFFER_SIZE;j++)
{ buffer[j] = 0;}
}
void *producer(void *param)
{
int item;
while(1)
{
item=item+1;
sem_wait(&empty);
pthread_mutex_lock(&mutex);
if(insert_item(item))
{
perror("Producer error.");
return 1;
}
else
{
printf("Producer produced %d\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
}
void *consumer(void *param)
{
int item;
while(1)
{
sleep(5);
sem_wait(&full);
pthread_mutex_lock(&mutex);
if(remove_item(item))
{
perror( "Consumer error.");
}
else
{
printf("Consumer consumed %d\n", item);
}
pthread_mutex_unlock(&mutex);
sem_post(&empty);
}
}
int insert_item(int item)
{
if(counter < BUFFER_SIZE)
{
buffer[counter] = item;
counter++;
return 0;
}
else
return -1;
}
int remove_item(int item)
{
if(counter > 0)
{
item = buffer[(counter-1)];
counter--;
return ;
}
else
return -1;
}
进行更改和更正后,我现在得到以下输出,这不是所需的.......
[root@localhost sree58]# gcc producerconsumer.c -lpthread -lrt
producerconsumer.c: In function ‘producer’:
producerconsumer.c:54: warning: return makes pointer from integer without a cast
[root@localhost sree58]# ./a.out
Producer produced 1804289383
Producer produced 846930886
Producer produced 1681692777
Producer produced 1714636915
Producer produced 1957747793
Producer produced 424238335
Producer produced 719885386
Producer produced 1649760492
Producer produced 596516649
Producer produced 1189641421
Consumer error.: Success
Producer produced 1025202362
Consumer error.: Illegal seek
Producer produced 1350490027
Consumer error.: Illegal seek
Producer produced 783368690
Consumer error.: Illegal seek
Producer produced 1102520059
Consumer error.: Illegal seek
Producer produced 2044897763
Consumer error.: Illegal seek
Producer produced 1967513926
Consumer error.: Illegal seek
Producer produced 1365180540
Consumer error.: Illegal seek
Producer produced 1540383426
Consumer error.: Illegal seek
Producer produced 304089172
Consumer error.: Illegal seek
Producer produced 1303455736
Consumer error.: Illegal seek
Producer produced 35005211
Consumer error.: Illegal seek
Producer produced 521595368
Consumer error.: Illegal seek
Producer produced 294702567
Consumer error.: Illegal seek
Producer produced 1726956429
请有人指导我......