linux多线程初学讨论
初学linux多线程,基本函数的意思也都理解,想做个程序实现个几个线程同时往一个缓冲区里放数据,几个线程取数据,程序放上来,希望能抛砖引玉,忘高手们给挑挑毛病,讲讲逻辑过程最好,看我理解的是否正确!谢谢!
#include<stdio.h>
#include<pthread.h>
#define SIZE 4
struct product
{
pthread_mutex_t mutex;
pthread_cond_t notfull;
pthread_cond_t notempty;
int pos;
int buf[SIZE];
};
void init(struct product *t)
{
pthread_mutex_init(&t->mutex,NULL);
pthread_cond_init(&t->notfull,NULL);
pthread_cond_init(&t->notempty,NULL);
t->pos =-1;
}
void put(struct product *t,int data)
{
pthread_mutex_lock(&t->mutex);
if((t->pos+1)>(SIZE-1))
pthread_cond_wait(&t->notfull,&t->mutex);
t->pos = t->pos +1;
t->buf[t->pos] = data;
printf("Thread %d put a data:%d to pos%d\n",pthread_self(),data,t->pos);
pthread_cond_broadcast(&t->notempty);
pthread_mutex_unlock(&t->mutex);
}
void get(struct product *t)
{
int rtntemp;
pthread_mutex_lock(&t->mutex);
if(t->pos<0)
pthread_cond_wait(&t->notempty,&t->mutex);
printf("Thread %d get a data:%d from pos%d\n",pthread_self(),t->buf[t->pos],t->pos);
rtntemp = t->buf[t->pos];
t->pos = t->pos -1;
pthread_cond_broadcast(&t->notfull);
pthread_mutex_unlock(&t->mutex);
}
struct product pdt;
void *putter()
{
int n;
for(n=0;n<8;n++)
put(&pdt,n);
}
void *getter()
{
int n;
for(n=0;n<8;n++)
get(&pdt);
}
int main(void)
{
pthread_t pt1,pt2,gt1,gt2;
void *retval;
init(&pdt);
pthread_create(&pt1,NULL,putter,0);
pthread_create(&pt2,NULL,putter,0);
pthread_create(>1,NULL,getter,0);
pthread_create(>2,NULL,getter,0);
pthread_join(pt1,&retval);
pthread_join(pt2,&retval);
pthread_join(gt1,&retval);
pthread_join(gt2,&retval);
return 0;
}
[解决办法]
太基础了,还是回去闷头学吧。