開発環境
- OS: macOS High Sierra - Apple
- IDE(統合開発環境): Xcode - Apple
- プログラミング言語: C
Head First C ―頭とからだで覚えるCの基本 (David Griffiths (著)、Dawn Griffiths (著)、中田 秀基 (監修)、木下 哲也 (翻訳)、オライリージャパン)の12章(スレッド - 並列の世界)、ビールマグネット(p. 509)を取り組んでみる。
ビールマグネット(p. 509)
//
// main.c
// sample
//
// Created by kamimura on 2018/03/12.
// Copyright © 2018 kamimura. All rights reserved.
//
#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(int argc, const char * argv[]) {
pthread_t threads[20];
printf("壁にはビールが%i本\n%i本のビール\n", beers, beers);
for (int t = 0; t < 20; t++) {
pthread_create(&threads[t], NULL, drink_lots, NULL);
}
void *result;
for (int t = 0; t < 20; t++) {
pthread_join(threads[t], &result);
}
printf("現在、壁にはビールが%i本あります。\n", beers);
return 0;
}
入出力結果(Terminal)
壁にはビールが2000000本 2000000本のビール 現在、壁にはビールが1069613本あります。 Program ended with exit code: 0
0 コメント:
コメントを投稿