linux下G++代码编译。。通过编译却运行出错。。。求帮忙!!

#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;
}

第1个回答  2012-03-27
逻辑错误
运行了一下,这是什么结果啊
./1.o: 1: ELF: not found
./1.o: 2: U‰õSH‰ûHcþ¾HƒìèH{‰kH‰ÇCÇC º1öèH{8‰ê1öèHƒÄH{X1Ò[]1öéHƒì¾1ÿèH: not found
./1.o: 2: $1ɺ1öè1ɺH‰ç1öèH‹: not found
./1.o: 2: cannot open öè1ÀHƒÄÃATU‰õSH‰ûH8LcèL‰çè‹CH‹ L‰çÿÀ™‰C÷{HcÒ‰,‘èH{Xè[‰è]AÃHƒì‹5苾¿1ÀèÿHƒÄÃATUSH‰ûHXHkèH‰ïè‹C H‹ H‰ïÿÀ™‰C ÷{HcÒD‹$‘èH{8è[]D‰àAÃHƒì苾¿1ÀèHƒÄÃProduce:%dConsumer:%d: No such file
./1.o: 2: $1öèH‹: not found
./1.o: 3: Syntax error: word unexpected (expecting ")")追问

要linux下g++ -o task1 task1.cpp lpthread

追答

运行提示 端错误
sbuf_init(ccc,2);这句出错,
你没初始化ccc,却在函数中访问他的成员
改了之后
pthread_join也出现段错误,搜了一下,也有人遇到过,我没解决

相似回答