- 论坛徽章:
- 0
|
- #include <stdio.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <stdlib.h>
- #define BUFFER_SIZE 10
- int buffer[BUFFER_SIZE];
- int in = 0;
- int out = 0;
- int nextProduced;
- int nextConsumed;
-
- void thread_producer(int *);
- void thread_consumer(int *,FILE * );
- int main(void)
- {
- FILE *fout;
- fout = fopen("data.out","w");
- pthread_t producer_id;
- pthread_t consumer_id;
- int ret_p, ret_c;
- ret_p = pthread_create(&producer_id,NULL,(void *) thread_producer,NULL);
- ret_c = pthread_create(&consumer_id,NULL,(void *) thread_consumer,NULL);
- if(ret_p!=0)
- {
- printf("Create thread_producer failed.\n");
- exit(1);
- }
- if(ret_c!=0)
- {
- printf("Create thread_consumer failed.\n");
- exit(1);
- }
- pthread_join(producer_id,NULL);
- pthread_join(consumer_id,NULL);
- fclose(fout);
- return 0;
- }
- void thread_producer(int* buffer)
- {
- while(1)
- {
- while(((in+1)%BUFFER_SIZE) == out)/* buffer is full */
- ;
- scanf("%d",&nextProduced);
- buffer[in] = nextProduced;
- in = (in+1)%BUFFER_SIZE;
- }
- return ;
- }
- void thread_consumer(int* buffer,FILE *fout)
- {
- while(1)
- {
- /*buffer is empty*/
- while(in == out)
- ;
- nextConsumed = buffer[out];
- fprintf(fout,"%d\n",nextConsumed);
- out = (out+1)%BUFFER_SIZE;
- }
- return ;
- }
复制代码 刚开始学操作系统,试着写了点,上来就错了阿。。誰来帮帮我阿。 |
|