- 论坛徽章:
- 0
|
本帖最后由 okocha-jay 于 2010-08-03 18:48 编辑
谢谢。做了个测试代码。暂时没问题
有错误,还需再改。- #include <stdio.h>
- #include <pthread.h>
- #define N 100000
- int a[N] = {0};
- volatile int r = 0; // index to a
- volatile int w = 0; // index to a
- #define NotFull (w <= N - 1)
- #define NotEmpty (r < w)
- // w 是由生产者修改, 消费者要访问的
- void * Pthread(void *arg) // 生产者
- {
- printf("producer %u\n", pthread_self());
- while ( NotFull )
- {
- usleep(1);
- a[w] = w; // 模仿Stevens的进程间通信书中例子
- ++w;
- }
- return 0;
- }
- void * Cthread(void *arg) // 消费者
- {
- printf("consumer %u\n", pthread_self());
- while ( NotEmpty || NotFull )
- {
- usleep(1);
- if ( !NotEmpty)//消费的太快了
- continue;
-
- if ( r != a[r] )
- printf("ERROR : a[%d] = %d\n", r, a[r]);
- ++ r;
- }
- }
- int main()
- {
- pthread_t prod, con;
- pthread_create(&prod, NULL, Pthread, NULL);
- pthread_create(&con, NULL, Cthread, NULL);
- pthread_join(prod, NULL) ;
- pthread_join(con, NULL) ;
-
- return 0;
- }
复制代码 |
|