Head First C ―頭とからだで覚えるCの基本
(オライリージャパン)
David Griffiths (著) Dawn Griffiths (著)
中田 秀基(監訳)(翻訳) 木下 哲也 (翻訳)
開発環境
- OS X Yosemite - Apple (OS)
- Emacs (CUI)、BBEdit - Bare Bones Software, Inc. (GUI) (Text Editor)
- C (プログラミング言語)
- LLVM/Clang (コンパイラ, Xcode - Apple)
Head First C ―頭とからだで覚えるCの基本(David Griffiths (著)、Dawn Griffiths (著) 中田 秀基(監訳)(翻訳)、木下 哲也 (翻訳)、オライリージャパン)の12章(スレッド: 並列の世界)、ビールマグネット(p.509)を解いてみる。
その他参考書籍
- 21st Century C: C Tips from the New School
- プログラミング言語C 第2版 ANSI規格準拠(B.W. カーニハンD.M. リッチー(著)、石田 晴久(翻訳)、共立出版)
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
- C実践プログラミング 第3版(Steve Oualline(著)、望月 康司 (監訳)(翻訳)、谷口 功(翻訳)、 オライリージャパン)
ビールマグネット(p.509)
コード(BBEdit, Emacs)
#include <stdio.h>
#include <pthread.h>
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++)
Stopif(pthread_create(&threads[t], NULL, drink_lots, NULL) == -1,
exit(1), "スレッドt[%i]を作成できません", t);
void* result;
for (int t = 0; t < 20; t++)
Stopif(pthread_join(threads[t], &result) == -1, exit(1),
"スレッドt[%i]をジョインできません。", t);
printf("現在壁にはビールが%i本あります\n", beers);
}
入出力結果(Terminal)
$ crun.sh sample509 clang ... 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが0本あります $ ./sample509 && ./sample509 && ./sample509 && ./sample509 && ./sample509 && ./sample509 && ./sample509 && ./sample509 && ./sample509 && ./sample509 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが0本あります 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが0本あります 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが0本あります 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが0本あります 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが0本あります 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが100000本あります 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが0本あります 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが100000本あります 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが0本あります 壁にはビールが2000000本 2000000本のビール 現在壁にはビールが0本あります $
0 コメント:
コメントを投稿