多线程编程模型之流水线模型

原例子在 第四章第一节。

文中的例子的代码写得实在太混乱。

重写后如下。

#include 
#include 
#include 

typedef struct state_tag
{
	pthread_mutex_t mutex;
	pthread_cond_t condAvail;
	long data;
	pthread_t pid;
	struct state_tag *next;
}stage_t;

typedef struct pipe_tag
{
	pthread_mutex_t mutex;
	stage_t *head;
	stage_t *tail;
	int stages;
}pipe_t;

#define true 1;
#define false 0;

void pipe_init( pipe_t *p )
{
	p->head = p->tail = NULL;
	p->stages = 0;
	pthread_mutex_init( &(p->mutex), NULL);
}

static int pipe_add_elem(pipe_t *p, stage_t *t)
{
	if( p == NULL )
	{
		//
		return false;
	}

	if(p->tail == NULL)
	{
		p->tail = p->head = t;
		return true;
	}
	
	p->tail->next = t;
	p->tail = t;

	return true;
}

int pipe_send(stage_t *st, long data)
{
	pthread_mutex_lock(&(st->mutex));

	st->data = data;
	
	pthread_cond_signal(&(st->condAvail));
	
	pthread_mutex_unlock(&(st->mutex));
	
		
}

void *pipe_stage(void *arg)
{
	stage_t *st = (stage_t *)arg;

	stage_t *next_st = st->next;

	while(1)
	{
		pthread_mutex_lock(&(st->mutex));
		
		fprintf(stderr, "myself addr:%p, next elem addr: %p\n", st, next_st);
		
		pthread_cond_wait(&(st->condAvail), &(st->mutex));
		
		if(next_st != NULL)
		{
			int newVal = st->data+1;
			pipe_send(next_st,newVal);
			
		}
		else
		{
			st->data += 1; 
			pthread_cond_signal( &(st->condAvail) );
		}
		
		pthread_mutex_unlock(&(st->mutex));

	}
}

int pipe_create(pipe_t *p, int stages)
{
	pthread_mutex_init(&(p->mutex), NULL);

	p->stages = stages;

	int i;

	for( i=0; inext = NULL;
		new_st->data = -1;
		pthread_mutex_init( &(new_st->mutex), NULL );
		pthread_cond_init( &(new_st->condAvail), NULL);

		pipe_add_elem(p, new_st);
	}

	stage_t *stIndex = NULL;

	for( stIndex = p->head; stIndex != NULL; stIndex = stIndex->next )
	{
		pthread_create(&(stIndex->pid), NULL, pipe_stage, (void *)stIndex);
	}

	return false;
}

int pipe_start(pipe_t *p, long value, int *allUp)
{
	pthread_mutex_lock(&(p->mutex));

	if( *allUp == 0)
	{
		sleep(2);
		
		*allUp = 1;
	}
	
	pipe_send(p->head, value);
	
	pthread_mutex_unlock(&(p->mutex));
}

int pipe_result(pipe_t *p, long *result)
{	

	pthread_mutex_lock(&(p->mutex));
	
	stage_t *tail = p->tail;

	pthread_mutex_unlock(&(p->mutex));
	
	
	pthread_mutex_lock(&(tail->mutex));
	
	pthread_cond_wait(&(tail->condAvail), &(tail->mutex));

	*result = tail->data;

	pthread_mutex_unlock(&(tail->mutex));

	
}

int main()
{
	pthread_setconcurrency( 11 );

	pipe_t p;
	
	pipe_init( &p );
	
	pipe_create(&p, 10);

	long c;
	
	int isAllThrUp = 0;

	while(1)
	{
		
		scanf("%ld", &c);
			
		pipe_start(&p, (long)c, &isAllThrUp);

		long val = -1;
		pipe_result(&p, &val);
		fprintf(stderr, "%ld\n", val);
	
	}
}

你可能感兴趣的:(multithread,architeture)