2018年7月12日木曜日

開発環境

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

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

コード

Makefile

CC = cc

all: sample run

sample: sample.c
 $(CC) sample.c -o sample

run: sample
 ./sample
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

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

int beers = 2000000;

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

int main() {
  pthread_t threads[20];

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

入出力結果(Terminal)

$ make
cc sample.c -o sample
./sample
壁にはビールが2000000本
2000000本のビール
現在、壁にはビールが1358700本あります
$ make
./sample
壁にはビールが2000000本
2000000本のビール
現在、壁にはビールが1660844本あります
$ make
./sample
壁にはビールが2000000本
2000000本のビール
現在、壁にはビールが1350981本あります
$ make
./sample
壁にはビールが2000000本
2000000本のビール
現在、壁にはビールが1148891本あります
$ make
./sample
壁にはビールが2000000本
2000000本のビール
現在、壁にはビールが1301220本あります
$ 

0 コメント:

コメントを投稿