|
产生两个线程,一个读,一个写,主要想试一下pthread_cond_wait()这个函数 编译没错,但运行老提示 段错误
void main ( void ){
pthread_t reader;
pthread_t writer;
//delay.tv_sec = 2;
//delay.tv_nec = 0;
pthread_mutex_init (&mutex,NULL);
pthread_cond_init(&cond,NULL);
pthread_create(&reader, NULL, (void *)&reader_function, NULL); 生成两个线程
pthread_create(&writer,NULL,(void*)&writer_function,NULL);
//writer_function( );
pthread_join(&reader,NULL);
pthread_join(&writer,NULL);
}
void writer_function (void){
while(1){
pthread_mutex_lock (&mutex);
while(buffer_has_item==1)
pthread_cond_wait(&cond,&mutex);
if (buffer_has_item==0){
buffer='a';
buffer_has_item=1;
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
}
}
void reader_function(void){
while(1){
pthread_mutex_lock(&mutex);
while(buffer_has_item==0)
pthread_cond_wait(&cond,&mutex);
if(buffer_has_item==1){
printf("buffer=%c\n",buffer);
buffer_has_item=0;
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
}
}
但是在主线程里用写函数,只生成一个线程的话,就没有错,但生成两个线程,主线程什么都不做的话,就提示有段错误 |
|