无论如何,我可以将此代码转换为使用Posix(p)线程而不是forks吗?我必须试验两者在内存和处理能力方面的差异。我正在测试不同数量的进程对处理器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;
}
答案 0 :(得分:0)
像这样的东西
#include <pthread.h>
void *cback(void *void_ptr)
{
int i;
float oldtotal=0, result=0;
for(i=0;i<2000000000;i++)
{
result=sqrt(1000.0)*sqrt(1000.0);
}
printf("Result is %f\n",result);
oldtotal = total; total = oldtotal + result;
printf("x increment finished\n");
return NULL;
}
int main ()
{
pthread_t onethread;
if (pthread_create(&onethread, NULL, cback, NULL) != 0)
{
printf("error creating thread\n");
}
}