#include"stdio.h" #include"pthread.h" #include"semaphore.h" static int datbuf[10] = {0}; static int n; sem_t sem1,sem2,sem3; void *do_input(void *pvoid) { int i; sem_wait(&sem1); printf("please input data\n"); for(i = 0;;i++) { scanf("%d",&datbuf[i]); n++; if(getchar()==‘\n‘) break; } sem_post(&sem2); pthread_exit(NULL); } void *do_swap(void *pvoid) { int i,j,min; sem_wait(&sem2); printf("data:\n"); for(i = 0; i<n;i++) { printf(" %d",datbuf[i]); } printf("\nswap:\n"); for(i = 0;i < n;i++) { for(j = 0;j<n-i-1;j++) if(datbuf[j]>datbuf[j+1]) { min = datbuf[j]; datbuf[j] = datbuf[j+1]; datbuf[j+1] = min; } } sem_post(&sem3); pthread_exit(NULL); } void *do_show(void *pvoid) { int i; sem_wait(&sem3); for(i = 0; i<n;i++) { printf(" %d",datbuf[i]); } sem_post(&sem1); pthread_exit(NULL); } int main() { pthread_t tid1,tid2,tid3; int ret; ret = sem_init(&sem1,0,1); ret += sem_init(&sem2,0,0); ret += sem_init(&sem3,0,0); if(ret != 0) { printf("Any semaphore inittialization failed\n"); return ret; } pthread_create(&tid1,NULL,&do_input,NULL); pthread_create(&tid2,NULL,&do_show,NULL); pthread_create(&tid3,NULL,&do_swap,NULL); pthread_join(tid1,NULL); pthread_join(tid2,NULL); pthread_join(tid3,NULL); return 0; }
时间: 2024-10-11 13:55:14