2014年3月4日火曜日

開発環境

Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の12章(スレッド)、ビールマグネット(p.509)を解いてみる。

その他参考書籍

ビールマグネット(p.509)

コード(BBEdit, Emacs)

sample480.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>

void error(char *msg)
{
  fprintf(stderr, "%s: %s\n", msg, strerror(errno));
  exit(1);
}

int beers = 2000000;
void *drink_lots(void *a)
{
  int i;
  for (i = 0; i < 100000; ++i) {
    beers = beers - 1;
  }
  return NULL;
}

int main()
{
  pthread_t threads[20];
  int t;
  printf("壁にはビールが%i本\n%i本のビール\n", beers, beers);
  for (t = 0; t < 20; ++t) {
    if (pthread_create(&threads[t], NULL, drink_lots, NULL) == -1) {
      char *var;
      sprintf(var, "スレッドthreads[%i]を作成できません", t);
      error(var);
    }
  }
  void *result;
  for (t = 0; t < 20; ++t) {
    if(pthread_join(threads[t], &result) == -1) {
      char *var;
      sprintf(var, "スレッドthredsp[%i]をジョインできません", t);
      error(var);
    }
  }
  printf("現在壁にはビールが%i本あります\n", beers);
  return (0);
}

Makefile

all: sample509

sample509: sample509.c
 cc -g -o sample509 sample509.c

clean:
 rm sample509

入出力結果(Terminal)

$ make && ./sample509
cc -g -o sample509 sample509.c
壁にはビールが2000000本
2000000本のビール
現在壁にはビールが854288本あります
$ ./sample509
壁にはビールが2000000本
2000000本のビール
現在壁にはビールが679353本あります
$ ./sample509
壁にはビールが2000000本
2000000本のビール
現在壁にはビールが800554本あります
$ ./sample509
壁にはビールが2000000本
2000000本のビール
現在壁にはビールが655527本あります
$ ./sample509
壁にはビールが2000000本
2000000本のビール
現在壁にはビールが474493本あります
$

0本にならないけどいいのかなぁ。

0 コメント:

コメントを投稿