baidu_32457989 2016-01-08 03:35 采纳率: 50%
浏览 1737

关于linux c语言多线程编程的问题

/* 以生产者和消费者模型问题来阐述Linux线程的控制和通信你
生产者线程将生产的产品送入缓冲区,消费者线程则从中取出产品。
缓冲区有N个,是一个环形的缓冲池。
*/
#include
#include

#define BUFFER_SIZE 16

struct prodcons
{
int buffer[BUFFER_SIZE];/*实际存放数据的数组*/
pthread_mutex_t lock;/*互斥体lock,用于对缓冲区的互斥操作*/
int readpos,writepos; /*读写指针*/
pthread_cond_t notempty;/*缓冲区非空的条件变量*/
pthread_cond_t notfull;/*缓冲区未满 的条件变量*/
};

/*初始化缓冲区*/
void pthread_init( struct prodcons *p)
{
pthread_mutex_init(&p->lock,NULL);
pthread_cond_init(&p->notempty,NULL);
pthread_cond_init(&p->notfull,NULL);
p->readpos = 0;
p->writepos = 0;
}

/*将产品放入缓冲区,这里是存入一个整数*/
void put(struct prodcons p,int data)
{
pthread_mutex_lock(&p->lock);
/
等待缓冲区未满*/
if((p->writepos +1)%BUFFER_SIZE ==p->readpos)
{
pthread_cond_wait(&p->notfull,&p->lock);
}
p->buffer[p->writepos] =data;
p->writepos++;
if(p->writepos >= BUFFER_SIZE)
p->writepos = 0;
pthread_cond_signal(&p->notempty);
pthread_mutex_unlock(&p->lock);
}
/*从缓冲区取出整数*/
int get(struct prodcons p)
{
int data;
pthread_mutex_lock(&p->lock);
/
等待缓冲区非空*/
if(p->writepos == p->readpos)
{
pthread_cond_wait(&p->notempty ,&p->lock);//非空就设置条件变量notempty
}
/*读书据,移动读指针*/
data = p->buffer[p->readpos];
p->readpos++;
if(p->readpos == BUFFER_SIZE)
p->readpos = 0;
/*设置缓冲区未满的条件变量*/
pthread_cond_signal(&p->notfull);
pthread_mutex_unlock(&p->lock);
return data;
}
/*测试:生产站线程将1 到1000的整数送入缓冲区,消费者线程从缓冲区中获取整数,两者都打印信息*/
#define OVER (-1)
struct prodcons buffer;
void producer(void *data)
{
int n;
for( n=0;n {
printf("%d ------>\n",n);
put(&buffer,n);
}
put(&buffer,OVER);
return NULL;
}
void *consumer(void *data)
{
int d;
while(1)
{
d = get(&buffer);
if(d == OVER)
break;
else
printf("----->%d\n",d);
}
return NULL;
}
int main()
{
pthread_t th_p,th_c;
void *retval;
pthread_init(&buffer);
pthread_create(&th_p,NULL,producer,0);
pthread_create(&th_c,NULL,consumer,0);
/
等待两个线程结束*/
pthread_join(th_p, &retval);
pthread_join(th_c,&retval);
return 0;
}

这段代码是我从网上下载的代码
问题是
main函数中没有声明结构体变量
也没有全局结构体变量
那么main函数为什么可以直接使用buffer

  • 写回答

1条回答 默认 最新

  • 你知我知皆知 2024-08-05 00:27
    关注

    以下回答参考 皆我百晓生券券喵儿 等免费微信小程序相关内容作答,并由本人整理回复。

    在C语言中,#include <stdio.h>#include <stdlib.h>是标准库头文件,它们包含了各种预定义常量、宏定义、函数等。这些头文件中的内容通常不需要用户进行编译时链接。

    然而,在某些情况下,为了方便用户编写程序,一些头文件可能被包含到源代码中,例如#include <pthread.h>,它包含了用于多线程编程的相关头文件。所以,当你看到#include <pthread.h>时,这并不意味着你需要直接在你的源代码中包含这个头文件,而是意味着你可以在这个位置开始编写有关多线程编程的内容。

    在你的代码中,#include <pthread.h>被包含到了#include <stdio.h>#include <stdlib.h>之间,因此主函数main()可以直接访问buffer结构体成员。由于#include <stdio.h>#include <stdlib.h>都是标准库头文件,它们不依赖于任何具体的源文件,所以main()可以直接使用buffer结构体成员。

    所以,你的代码没有错误,可以在main()中使用buffer结构体成员。

    评论

报告相同问题?