当前位置: 技术问答>linux和unix
(菜鸟飞飞)问个多线程的程序的问题
来源: 互联网 发布时间:2016-09-05
本文导语: #include #include #include #include #include #include #include #include #include #include void reader_function ( void ); void writer_function ( void ); char buffer; int buffer_has_item=0; pthread_mutex_t mutex; struct timespec delay; main (){ pthread_t reader; ...
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
void reader_function ( void );
void writer_function ( void );
char buffer;
int buffer_has_item=0;
pthread_mutex_t mutex;
struct timespec delay;
main (){
pthread_t reader;
/* 定义延迟时间*/
delay.tv_sec = 2;
delay.tv_nsec = 0;
/* 用默认属性初始化一个互斥锁对象*/
pthread_mutex_init(&mutex,NULL);
pthread_create(&reader,pthread_attr_default,(void *)&reader_function),NULL);
writer_function();
}
void writer_function (void){
while(1){
/* 锁定互斥锁*/
pthread_mutex_lock (&mutex);
if (buffer_has_item==0){
buffer=make_new_item( );
buffer_has_item=1;
}
/* 打开互斥锁*/
pthread_mutex_unlock(&mutex);
pthread_delay_np(&delay);
}
}
void reader_function(void){
while(1){
pthread_mutex_lock(&mutex);
if(buffer_has_item==1){
consume_item(buffer);
buffer_has_item=0;
}
pthread_mutex_unlock(&mutex);
pthread_delay_np(&delay);
}
}
报错为:[root@localhost C]# gcc -g reader.c -o reader -lpthread
reader.c: In function ‘main’:
reader.c:25: 错误:‘pthread_attr_default’ 未声明 (在此函数内第一次使用)
reader.c:25: 错误:(即使在一个函数内多次出现,每个未声明的标识符在其
reader.c:25: 错误:所在的函数内只报告一次。)
reader.c:25: 错误:提供给函数 ‘pthread_create’ 的实参太少
reader.c:25: 错误:expected ‘;’ before ‘)’ token
reader.c:25: 错误:expected statement before ‘)’ token
谢谢回答!!
|
pthread_attr_default没有定义,用NULL代替即可。
man pthread_create 里面提到的:
If attr is NULL, the default attributes shall be used.
通过编译之后,多半还会有链接问题:
test.c:(.text+0x6a): undefined reference to `make_new_item'
test.c:(.text+0x93): undefined reference to `pthread_delay_np'
test.c:(.text+0xc2): undefined reference to `consume_item'
据说pthread_delay_np是solaris的,linux没有实现。另外两个可能要自己写。
http://bbs.chinaunix.net/archiver/?tid-584593.html
http://linux.chinaunix.net/bbs/archiver/?tid-282797.html
man pthread_create 里面提到的:
If attr is NULL, the default attributes shall be used.
通过编译之后,多半还会有链接问题:
test.c:(.text+0x6a): undefined reference to `make_new_item'
test.c:(.text+0x93): undefined reference to `pthread_delay_np'
test.c:(.text+0xc2): undefined reference to `consume_item'
据说pthread_delay_np是solaris的,linux没有实现。另外两个可能要自己写。
http://bbs.chinaunix.net/archiver/?tid-584593.html
http://linux.chinaunix.net/bbs/archiver/?tid-282797.html
|
有时候一个简单的错误很难发现却是致命的...
|
语法错误可以用一个优秀的编辑器来帮你检测