【发布时间】:2014-03-17 22:09:47
【问题描述】:
我是否可以将此代码转换为使用 Posix (p) 线程而不是分叉?我必须试验两者在内存和处理能力方面的差异。我正在测试不同数量的进程对处理器 CPU% 的影响,具体取决于内核数。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define N 16 /* define the total number of processes we want */
float total=0;
int compute()
{
int i;
float oldtotal=0, result=0;
the arbitrary number 1000 */
for(i=0;i<2000000000;i++)
{
result=sqrt(1000.0)*sqrt(1000.0);
}
/* Print the result \u2013 should be no surprise */
printf("Result is %f\n",result);
oldtotal = total;
total = oldtotal + result;
/* Print running total so far. */
printf("Total is %f\n",total);
return(0);
}
int main()
{
int pid[N], i, j;
float result=0;
printf("\n");
for(i=0;i<N;i++)
{
if((pid[i]=fork())==-1)
{
exit(1);
}
else if(pid[i] > 0)
{
/* give a message about the proc ID */
printf("Process Id for process %d is %d\n",i,getpid());
/* call the function to do some computation. */
compute();
break;
}
}
return 0;
}
【问题讨论】:
-
你有什么尝试吗?首先你必须使用 pthread_create() 开始创建线程。
-
父进程而不是子进程进行计算似乎很奇怪——所以实际上有一个奇怪的进程结构。请注意,一旦孩子被分叉,分叉的进程就不会共享全局变量
total。在线程代码中,您必须提供访问控制(互斥锁)来保护全局变量total。否则,看起来并不太难。 -
编译时开启优化,例如使用
gcc -O2,for(i=0;i<2000000000;i++) result=sqrt(1000.0)*sqrt(1000.0);将被删除。尝试计算一些重要的东西,也许是for(i=0;i<2000000000;i++) result=sqrt(1000.0)*sqrt(result+0.1);