|
发表于 2004-11-4 15:13:50
|
显示全部楼层
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<errno.h>
int buff[5];
void pro_th(void *arg);
void cus_th(void *arg);
pthread_mutex_t mutex;
int main(int argc,char argv[])
{
pthread_t pro_th_id;
pthread_t cus_th_id;
int ret;
//create threads
ret=pthread_create(&pro_th_id,NULL,(void *)pro_th,NULL);
if(ret!=0){
perror("pthread_create:pro_th");
exit(EXIT_FAILURE);
}
ret=pthread_create(&cus_th_id,NULL,(void *)cus_th,NULL);
if(ret!=0){
perror("pthread_create:cus_th");
exit(EXIT_FAILURE);
}
//create mutex
int mu;
mu=pthread_mutex_init(&mutex,NULL);
if(mu!=0){
perror("pthread_mutex_init");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
void pro_th(void *arg)
{ if(pthread_mutex_lock(&mutex)!=0){
perror("pthread_mutex_lock");
exit(EXIT_FAILURE);
}
int i;
for(i=0;i<5;i++){
buff=i;
printf("pro_th put the produce into the buffer and sleep for 2s");
sleep(2);
}
if(pthread_mutex_unlock(&mutex)!=0){
perror("pthread_mutex_unlock");
exit(EXIT_FAILURE);
}
}
void cus_th(void *arg)
{ int ret;
ret=pthread_mutex_trylock(&mutex);
if(ret!=EBUSY){
if(ret!=0){
perror("pthread_mutex_trylock");
exit(EXIT_FAILURE);
}
printf("The muxte is unlock, cus_th will read form the buffer...\n");
printf("The produce in buffer is:");
int i;
for(i=0;i<5;i++){
printf(" d%",buff);
}
}else{
printf("The mutex is locked,cus_th waiting for producing");
}
}
用GCC编译时好象在连接时有错误.(gcc -o pro pro.c).
关键是现在看不懂出错信息是什么意思,本人接触linux下编程不久啦,请教高手. |
|