#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
typedef struct{
int *buf;
int n;
int front;
int rear;
sem_t mutex;
sem_t slots;
sem_t items;
}sbuf_t;
void *thread1(void *varg);
void *thread2(void *varg);
void sbuf_init(sbuf_t *sp, int n);
int sbuf_insert(sbuf_t *sp,int item);
int sbuf_remove(sbuf_t *sp);
sbuf_t *ccc;
int i;
int main()
{
sbuf_t *ccc;
pthread_t tid1,tid2;
sbuf_init(ccc,2);
pthread_create(&tid1, NULL, thread1,NULL);
pthread_create(&tid2, NULL, thread2,NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
}
void *thread1(void *varg){
sbuf_t *ccc=(sbuf_t*)varg;
sbuf_insert(ccc,i);
printf("Produce:%d",i);
i++;
}
void *thread2(void *varg){
sbuf_t *abc=(sbuf_t*)varg;
sbuf_remove(abc);
printf("Consumer:%d\n",i);
}
void sbuf_init(sbuf_t *sp,int n)
{
sp->buf = (int*)calloc(n,sizeof(int));
sp->n = n; /* Buffer holds max of n items */
sp->front = sp->rear = 0; /* Empty buffer iff front == rear */
sem_init(&sp->mutex,0,1); /* Binary semaphore for locking */
sem_init(&sp->slots,0,n); /* Initially, buf has n empty slots */
sem_init(&sp->items,0,0); /* Initially, buf has 0 data items */
}
int sbuf_insert(sbuf_t *sp, int item)
{
sem_wait(&sp->slots); /* Wait for available slot */
sem_wait(&sp->mutex); /* Lock the buffer */
sp->buf[(++sp->rear)%(sp->n)] = item; /* Insert the buffer */
sem_post(&sp->mutex); /* Unlock the buffer */
sem_post(&sp->items); /* Announce available item */
return item;
}
int sbuf_remove(sbuf_t *sp)
{
int item;
sem_wait(&sp->items); /* Wait for available item */
sem_wait(&sp->mutex); /* Lock the buffer */
item = sp->buf[(++sp->front)%(sp->n)]; /* Remove the item */
sem_post(&sp->mutex); /* Unlock the buffer */
sem_post(&sp->slots); /* Announce available slot */
return item;
}
要linux下g++ -o task1 task1.cpp lpthread
追答运行提示 端错误
sbuf_init(ccc,2);这句出错,
你没初始化ccc,却在函数中访问他的成员
改了之后
pthread_join也出现段错误,搜了一下,也有人遇到过,我没解决