teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

yohhoyさんのアドバイスより、appleをatomicへ変更

2020/06/12 09:35

投稿

Chironian
Chironian

スコア23274

answer CHANGED
@@ -7,6 +7,7 @@
7
7
  ```C++
8
8
  #include <thread>
9
9
  #include <mutex>
10
+ #include <atomic>
10
11
  #include <chrono>
11
12
  #include <algorithm>
12
13
  #include <iostream>
@@ -22,7 +23,7 @@
22
23
  int b=0;
23
24
 
24
25
  {
25
- int apple=100;
26
+ std::atomic_int apple=100;
26
27
 
27
28
  std::mutex mutex;
28
29
 
@@ -36,7 +37,7 @@
36
37
  {
37
38
  std::lock_guard<std::mutex> lock(mutex);
38
39
  sleep(1); // りんご購入
39
- int buy=std::min(5, apple);
40
+ int buy=std::min(5, static_cast<int>(apple));
40
41
  apple -= buy;
41
42
  a += buy;
42
43
  }
@@ -56,7 +57,7 @@
56
57
  {
57
58
  std::lock_guard<std::mutex> lock(mutex);
58
59
  sleep(2); // りんご購入
59
- int buy=std::min(3, apple);
60
+ int buy=std::min(3, static_cast<int>(apple));
60
61
  apple -= buy;
61
62
  b += buy;
62
63
  }
@@ -72,4 +73,4 @@
72
73
  std::cout << "b=" << b << "\n";
73
74
  }
74
75
  ```
75
- [wandbox](https://wandbox.org/permlink/jy5Zzmph8SbuGoLz)
76
+ [wandbox](https://wandbox.org/permlink/DUUQxDhIJR7OoYvo)