- 论坛徽章:
- 19
|
- /*
- * Main.c
- *
- * Created on: 2013年7月19日
- * Author: root
- */
- #include "ConcurrentPrimeFinder.h"
- #include <stdio.h>
- #include <time.h>
- int main(int argc, char *argv[]) {
- time_t start, end;
- ConcurrentPrimeFinder finder;
- time(&start);
- int sum = finder.countPrime(10000000);
- time(&end);
- printf("0-10000000之间有%ld个素数\n", sum);
- printf("程序运行时间%d秒\n", end - start);
- return 0;
- }
复制代码- /*
- * ConcurrentPrimeFinder.h
- *
- * Created on: 2013年7月19日
- * Author: root
- */
- #ifndef CONCURRENTPRIMEFINDER_H_
- #define CONCURRENTPRIMEFINDER_H_
- #include <boost/thread.hpp>
- #include <stdio.h>
- class ConcurrentPrimeFinder {
- public:
- ConcurrentPrimeFinder();
- virtual ~ConcurrentPrimeFinder();
- int countPrime(long number);
- private:
- int poolsize;
- };
- #endif /* CONCURRENTPRIMEFINDER_H_ */
复制代码- /*
- * ConcurrentPrimeFinder.cpp
- *
- * Created on: 2013年7月19日
- * Author: root
- */
- #include "ConcurrentPrimeFinder.h"
- ConcurrentPrimeFinder::ConcurrentPrimeFinder() {
- poolsize = 4;
- }
- ConcurrentPrimeFinder::~ConcurrentPrimeFinder() {
- }
- bool isPrime(long number) {
- if (1 >= number) {
- return false;
- }
- long i;
- for (i = 2; i <= sqrt(number); i++) {
- if (0 == number % i) {
- return false;
- }
- }
- return true;
- }
- void countPrimeInRange(long int lower, long int upper, int *total, bool *flag) {
- long i = 0;
- for (i = lower; i < upper; i++) {
- if (isPrime(i)) {
- (*total)++;
- }
- }
- *flag = true;
- }
- int ConcurrentPrimeFinder::countPrime(long number) {
- using namespace boost;
- int total = 0, sum[4] = { 0 };
- bool flag[4] = { false };
- long start = 0, end = 0;
- long range = number / poolsize;
- int volatile i = 0;
- for (i = 0; i < poolsize; i++) {
- start = range * i;
- if (i < poolsize - 1) {
- end = start + range;
- } else {
- end = number;
- }
- thread mythread(
- bind(&countPrimeInRange, start, end, &(sum[i]), &(flag[i])));
- }
- i = 0;
- while (i < poolsize) {
- if (flag[i]) {
- total += sum[i];
- i++;
- }
- }
- return total;
- }
复制代码 运行结果- 0-10000000之间有664579个素数
- 程序运行时间5秒
复制代码 |
|