首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将forks转换为pthread

将forks转换为pthread
EN

Stack Overflow用户
提问于 2014-03-18 06:09:47
回答 1查看 858关注 0票数 0

有没有什么办法可以将这段代码转换为使用Posix (p)线程而不是fork?我必须对两者在内存和处理能力方面的差异进行实验。我正在测试不同数量的进程对处理器CPU%的影响,这取决于内核的数量。

代码语言:javascript
复制
#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; 
} 
EN

回答 1

Stack Overflow用户

发布于 2014-03-18 06:39:24

像这样的东西

代码语言:javascript
复制
#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");
}

}

请参阅man pagetutorial

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22466533

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档