Linuxプログラム設計第2版練習問題(第8章)

2509 ワード

1、Fibonacciシーケンスは0、1、1、2、3......、通常、......
#include 
#include 
#include 
#include 
int arr_fib[100];
int fib(int n)
{
	if(n==0)
		return 0;
	else if(n==1||n==2)
		return 1;
	else
		return(fib(n-1)+fib(n-2));
}
void *print_fib(void *n)
{
	int i;
	int fib_num;
	for(i=0;i
4、既存の4つのスレッドR 1,R 2,W 1,W 2は、1つの数のバッファBを共有することができる.スレッドR 1は、キーボードから投入された数をバッファBに毎回格納し、スレッドW 1の印刷出力を行う.スレッドR 2は、ディスクから読み出されるたびにバッファBに格納され、スレッドW 2が出力を印刷する.1つのスレッドがデータをバッファに格納した後、印刷出力されないまで、どのスレッドもバッファに格納しないでください.バッファに新しい数が格納されない前に、バッファからの印刷の取り出しを高速化するスレッドは許可されません.プログラミング......
#include 
#include 
#include 
#include 
#include 
pthread_mutex_t S;
sem_t S1,S2;
int num;
int f1=0,f2=0;
void *R1()
{
	while(1)
	{
	pthread_mutex_lock(&S);
	if(f1==0&&f2==0)
	{
		int a;
		printf("      :");
		scanf("%d",&a);
		num=a;
		printf("R1      B   %d
",num); sem_post(&S1); f1=1; } pthread_mutex_unlock(&S); } } void *R2() { FILE *fp=fopen("file3.dat","r"); while(!feof(fp)) { pthread_mutex_lock(&S); if(f2==0&&f1==0) { fscanf(fp,"%d",&num); printf("R2 B %d
",num); sem_post(&S2); f2=1; } pthread_mutex_unlock(&S); } fclose(fp); } void *W1() { while(1) { pthread_mutex_lock(&S); if(f1==1) { sem_wait(&S1); printf("R1num=%d
",num); f1=0; } pthread_mutex_unlock(&S); } } void *W2() { while(1) { pthread_mutex_lock(&S); if(f2==1) { sem_wait(&S2); printf("R2num=%d
",num); f2=0; } pthread_mutex_unlock(&S); } } int main() { pthread_t tid1,tid2,tid3,tid4; pthread_mutex_init(&S,NULL); sem_init(&S1,0,0); sem_init(&S2,0,0); pthread_create(&tid1,NULL,R1,NULL); pthread_create(&tid2,NULL,R2,NULL); pthread_create(&tid3,NULL,W1,NULL); pthread_create(&tid4,NULL,W2,NULL); pthread_join(tid1,NULL); pthread_join(tid2,NULL); pthread_join(tid3,NULL); pthread_join(tid4,NULL); pthread_mutex_destroy(&S); sem_destroy(&S1); sem_destroy(&S2); return 0; }