本文介绍了三种构建线程解决方案的方式。
一、流水线:每个线程执行同一种操作,并把操作结果传递给下一步骤的线程。
代码示例如下:
终端输入一个int值,每个线程将该值加1,并将结果传给下一个线程。
#include<stdio.h> #include<pthread.h> typedef struct stage_tag { pthread_mutex_t mutex; pthread_cond_t cond; int data; int ready; pthread_t tid; struct stage_tag *next; }stage_t; typedef struct pipe_tag { pthread_mutex_t mutex; stage_t *head; stage_t *tail; int stages; }pipe_t; void pipe_send(stage_t *stage,int data) { stage->data =data; stage->ready = 1; pthread_cond_signal(&stage->cond); } void *thread_route(void *arg) { stage_t *stage = (stage_t *)arg; while(!stage->ready) { pthread_cond_wait(&stage->cond,&stage->mutex); } int data = stage->data+1; stage_t *next = stage->next; if(next!=NULL) { pipe_send(next,data); } return NULL; } void create_pipe(pipe_t *pipe,int stages) { // pipe = (pipe_t *)malloc(sizeof(pipe_t)); pipe->stages = stages; int i; stage_t *stage; stage_t *last; for(i=0;i<=stages;i++) { stage = (stage_t *)malloc(sizeof(stage_t)); stage->data = i; if(i==0) { pipe->head = stage; } if(last!=NULL) { last->next = stage; } last = stage; } last->next=NULL; pipe->tail = last; for(stage=pipe->head;stage->next!=NULL;stage=stage->next) { pthread_create(&stage->tid,NULL,thread_route,(void *)stage); printf("stage %d\n",stage->data); } /* free(pipe); for(stage=pipe->head;stage!=NULL;stage=stage->next) { free(stage); } */ } int main(void) { pipe_t my_pipe; long value,result; char line[128]; create_pipe(&my_pipe,10); pipe_send(my_pipe.head,5); sleep(10); printf("result is %d\n",my_pipe.tail->data); return 0; }