vs2008环境下pthread程序的编译运行——以多线程求π为例

一、准备工作

首先从 http://sourceware.org/pthreads-win32/#download 

下载pthreads-w32-2-9-1-release.rar,解压后得到Pre-built.2文件夹

将其中的lib文件夹和include文件夹内容分别放到vs2008相应位置。

将其中dll文件夹中的文件与编译生成的exe放在同一目录下(一般为vs2008工程目录的Dubug或Release目录)。

二、程序编写

求π值近似公式:

 

程序源代码如下:

 1 // exp1_pi.cpp : 定义控制台应用程序的入口点。
 2 //
 3 #include "stdafx.h"
 4 #include<stdlib.h>
 5 #include <pthread.h>
 6 #include<iostream>
 7 using namespace std;
 8 
 9 #pragma comment (lib,"pthreadVC2.lib")
10 
11 int n = 0;
12 int threadnum = 0;
13 double sum = 0;
14 
15 //初始化锁变量
16 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
17 
18 //线程函数,根据线程rank确定自身计算范围,进行计算,并将计算结果加至全局变量sum中
19 void* Thread_sum(void* rank)
20 {
21     long my_rank = (long) rank;
22     double factor;
23     double my_sum = 0;
24     long long i; 
25     long long my_n = n/threadnum;
26     long long my_first_i = my_n * my_rank;
27     long long my_last_i = my_first_i + my_n;
28 
29     if(my_first_i % 2 ==0)
30         factor = 1.0;
31     else
32         factor = -1.0;
33 
34     for(i = my_first_i; i < my_last_i; i++, factor = -factor)
35     {
36         my_sum += factor/(2*i+1);
37     }
38 
39     //使用锁变量,保证对sum赋值操作的互斥性
40     pthread_mutex_lock(&mutex);
41     sum += my_sum;
42     pthread_mutex_unlock(&mutex);
43 
44     return NULL;
45 }
46 
47 int main(int argc, char *argv[]) {
48 
49 
50     //从main函数接收参数,n为问题规模,threadnum为线程个数
51     //n = atoi(argv[1]);
52     //threadnum=atoi(argv[2]);
53     n = 10000;
54     threadnum = 8;
55 
56     pthread_t *calculator = new pthread_t[threadnum];
57 
58     //启动各个线程
59     for(int rank = 0; rank < threadnum; rank++)
60     {
61         pthread_create(&calculator[rank],NULL,Thread_sum,(void*)rank);    
62     }
63 
64     //主线程等待所有线程结束
65     for(int j = 0;j<threadnum;j++)
66     {
67         pthread_join(calculator[j],NULL);
68     }
69 
70     double pi = sum * 4.0;
71     //输出pi的值,精确到小数点后15位
72     printf("pi: %.15lf\n",pi);
73     system("pause");
74 
75     return 0;
76 }

三、程序运行结果

转载于:https://www.cnblogs.com/rufa/archive/2013/05/09/3069037.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值