Head First C ―頭とからだで覚えるCの基本
(オライリージャパン)
David Griffiths (著) Dawn Griffiths (著)
中田 秀基(監訳)(翻訳) 木下 哲也 (翻訳)
開発環境
- OS X Mavericks - Apple(OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- Clang (コンパイラ)
Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の12章(スレッド)、ビールマグネット(p.509)を解いてみる。
その他参考書籍
- プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
- C実践プログラミング 第3版 (Steve Oualline (著)、 望月 康司 (監訳) (翻訳)、 谷口 功 (翻訳)、 オライリージャパン)
ビールマグネット(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 コメント:
コメントを投稿