C 将fork转换为pthread
我是否可以将此代码转换为使用Posix(p)线程而不是fork?我必须对两者在记忆和处理能力上的差异进行实验。我正在测试不同数量的进程对处理器CPU%的影响,这取决于内核的数量C 将fork转换为pthread,c,linux,pthreads,fork,C,Linux,Pthreads,Fork,我是否可以将此代码转换为使用Posix(p)线程而不是fork?我必须对两者在记忆和处理能力上的差异进行实验。我正在测试不同数量的进程对处理器CPU%的影响,这取决于内核的数量 #include <stdio.h> #include <stdlib.h> #include <math.h> #define N 16 /* define the total number of processes we want */ float total=0;
#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;
}
#包括
#包括
#包括
#定义N 16/*定义我们想要的进程总数*/
浮动总数=0;
int compute()
{
int i;
float oldtoal=0,result=0;
任意数1000*/
对于(i=0;i类似的东西
#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");
}
}
#包括
void*cback(void*void\u ptr)
{
int i;
float oldtoal=0,result=0;
对于(i=0;iDid)您是否尝试了任何操作?首先,您必须使用pthread_create()开始创建线程。父进程而不是子进程进行计算似乎有些奇怪-因此实际上存在一个奇怪的进程结构。请注意,一旦子进程分叉,分叉进程就不会共享全局变量total
。在线程化代码中,您必须提供访问控制(互斥)要保护全局变量total
。否则,看起来不会太困难。在编译时启用优化,例如使用gcc-O2
for(i=0;iSo)的,这到底在做什么?我可以使用gcc-o4test4test.o-lm-static-pthread
编译代码,但运行时没有输出。