设计思路:
对于这个问题,可以创建四个线程:两个生产者(Provider)和两个消费者(Customer),它们分别进行将已使用的数字放入大小为8的缓冲区,和从缓冲区取出一个数字打印到屏幕上。假定每个生产者一次生产一个已被取出的数字,每个消费者一次取出一个数字打印到屏幕上。
具体实现时,我们将信号量(Semaphore)初始化为0,如此消费者必定需要等待生产者生产出至少一个资源才能使用资源。如此反复,实现同步。
源代码如下:
---------------
-
-
-
-
-
-
-
-
-
-
- #include <stdio.h>
- #include <stdlib.h>
-
- #include <pthread.h>
- #include <semaphore.h>
-
-
- #define BUFFERSIZE 8
-
- int bufArray[BUFFERSIZE];
-
-
- sem_t mySem;
-
-
- void provider1()
- {
- int i;
- while ( 1 )
- {
-
- for ( i = 0; i < BUFFERSIZE; i++ )
- {
- if ( -1 == bufArray[i] )
- {
- printf("provider1 is working, it provided the number %d.\n", i);
- bufArray[i] = i;
-
- sem_post( &mySem );
- break;
- }
- }
- }
- }
-
-
- void customer1()
- {
- int i;
- while ( 1 )
- {
- sem_wait( &mySem );
-
- for ( i = 0; i < BUFFERSIZE; i++ )
- {
- if ( -1 != bufArray[i] )
- {
- printf("customer1 is working, it consumed the number %d.\n", i);
- bufArray[i] = -1;
- break;
- }
- }
- }
- }
-
-
- void provider2()
- {
- int i;
- while ( 1 )
- {
-
- for ( i = BUFFERSIZE - 1; i > -1; i-- )
- {
- if ( -1 == bufArray[i] )
- {
- printf("provider2 is working, it provided the number %d.\n", i);
- bufArray[i] = i;
-
- sem_post( &mySem );
- break;
- }
- }
- }
- }
-
-
- void customer2()
- {
- int i;
- while ( 1 )
- {
- sem_wait( &mySem );
-
- for ( i = BUFFERSIZE - 1; i > -1; i-- )
- {
- if ( -1 != bufArray[i] )
- {
- printf("customer2 is working, it consumed the number %d.\n", i);
- bufArray[i] = -1;
- break;
- }
- }
- }
- }
-
- int main()
- {
- int i;
- pthread_t pro1, pro2, cus1, cus2;
-
-
- for ( i = 0; i < BUFFERSIZE; i++ )
- bufArray[i] = -1;
-
-
- sem_init( &mySem, 0, 0 );
-
-
- pthread_create( &pro1, NULL, (void *) provider1, NULL );
- pthread_create( &pro2, NULL, (void *) provider2, NULL );
- pthread_create( &cus1, NULL, (void *) customer1, NULL );
- pthread_create( &cus2, NULL, (void *) customer2, NULL );
-
-
- pthread_join( pro1, NULL );
- pthread_join( pro2, NULL );
- pthread_join( cus1, NULL );
- pthread_join( cus2, NULL );
-
- return 0;
- }
-------------
执行结果:(程序循环执行过程中的一段)
从执行结果可以看到,两个生产者与两个消费者的执行顺序由于系统的调度而变得不确定, 但是两者之间是相互影响的,生产者需要生产消费者使用完的资源,消费者只能使用生产者已经生产的资源。
最先工作的线程如果是消费者,信号量mySem的值将会是0;如此线程被中断,直到生产者线程工作,生产资源,每生产一个资源mySem的值增加一,消费者才能使用资源,使用一个资源mySem减少一。此后生产者工作时会查看资源数组bufArray中的资源是否被使用,如果被使用则补充该资源。这样消费者与生产者之间的消费与生产活动就同步起来了。
相关问题
由于系统调度的缘故,可能程序的执行结果,在一段时间之内是一个生产者与 一个消费者不断的生产与消费,这在逻辑上也是成立的。
(yangqiang1989) |