OLD | NEW |
(Empty) | |
| 1 // Copyright 2013 The Chromium Authors. All rights reserved. |
| 2 // Use of this source code is governed by a BSD-style license that can be |
| 3 // found in the LICENSE file. |
| 4 |
| 5 #include <stdio.h> |
| 6 |
| 7 #include "base/at_exit.h" |
| 8 #include "base/bind.h" |
| 9 #include "base/bind_helpers.h" |
| 10 #include "base/callback.h" |
| 11 #include "base/location.h" |
| 12 #include "base/message_loop/message_loop.h" |
| 13 #include "base/run_loop.h" |
| 14 #include "base/strings/string_number_conversions.h" |
| 15 #include "base/task_runner.h" |
| 16 #include "base/threading/thread.h" |
| 17 #include "base/time/time.h" |
| 18 |
| 19 namespace { |
| 20 |
| 21 bool FindNonTrivialFactor(int n, int* factor) { |
| 22 // Really naive algorithm. |
| 23 for (int i = 2; i < n; ++i) { |
| 24 if (n % i == 0) { |
| 25 *factor = i; |
| 26 return true; |
| 27 } |
| 28 } |
| 29 return false; |
| 30 } |
| 31 |
| 32 void FindNonTrivialFactorHelper(int n, int* factor, bool* found) { |
| 33 *found = FindNonTrivialFactor(n, factor); |
| 34 } |
| 35 |
| 36 void PrintStatusUpdate(base::Time start_time) { |
| 37 double num_seconds = (base::Time::Now() - start_time).InSecondsF(); |
| 38 printf("Waited for %f seconds...\n", num_seconds); |
| 39 } |
| 40 |
| 41 void PrintStatusUpdateRepeatedly( |
| 42 const scoped_refptr<base::TaskRunner>& task_runner, |
| 43 base::Time start_time, |
| 44 base::TimeDelta print_interval) { |
| 45 PrintStatusUpdate(start_time); |
| 46 task_runner->PostDelayedTask(FROM_HERE, |
| 47 base::Bind(PrintStatusUpdateRepeatedly, |
| 48 task_runner, |
| 49 start_time, |
| 50 print_interval), |
| 51 print_interval); |
| 52 } |
| 53 |
| 54 } // namespace |
| 55 |
| 56 int main(int argc, char* argv[]) { |
| 57 base::AtExitManager exit_manager; |
| 58 |
| 59 if (argc <= 1) { |
| 60 printf("%s: missing operand\n", argv[0]); |
| 61 return -1; |
| 62 } |
| 63 |
| 64 int n = 0; |
| 65 if (!base::StringToInt(argv[1], &n) || n < 2) { |
| 66 printf("%s: invalid n `%s'\n", argv[0], argv[1]); |
| 67 return -1; |
| 68 } |
| 69 |
| 70 base::Thread worker_thread("Worker thread"); |
| 71 CHECK(worker_thread.Start()); |
| 72 |
| 73 base::MessageLoop main_loop; |
| 74 |
| 75 base::RunLoop run_loop; |
| 76 |
| 77 int factor = 0; |
| 78 bool found = false; |
| 79 worker_thread.message_loop_proxy()->PostTaskAndReply( |
| 80 FROM_HERE, |
| 81 base::Bind(&FindNonTrivialFactorHelper, n, &factor, &found), |
| 82 run_loop.QuitClosure()); |
| 83 |
| 84 PrintStatusUpdateRepeatedly(main_loop.message_loop_proxy(), |
| 85 base::Time::Now(), |
| 86 base::TimeDelta::FromSeconds(1)); |
| 87 |
| 88 run_loop.Run(); |
| 89 |
| 90 worker_thread.Stop(); |
| 91 |
| 92 if (found) { |
| 93 printf("found non-trivial factor %d for %d\n", factor, n); |
| 94 DCHECK_EQ(n % factor, 0); |
| 95 } else { |
| 96 printf("%d is prime\n", n); |
| 97 } |
| 98 |
| 99 return 0; |
| 100 } |
OLD | NEW |