【问题标题】:Converting forks into pthreads将 fork 转换为 pthread
【发布时间】: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 -O2for(i=0;i&lt;2000000000;i++) result=sqrt(1000.0)*sqrt(1000.0); 将被删除。尝试计算一些重要的东西,也许是for(i=0;i&lt;2000000000;i++) result=sqrt(1000.0)*sqrt(result+0.1);

标签: c linux pthreads fork


【解决方案1】:

类似的东西

#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

【讨论】:

  • 那么这到底是在做什么呢?我可以使用gcc -o 4test 4test.o -lm -static -pthread编译代码,但是运行时没有输出。
猜你喜欢
  • 2020-08-17
  • 2010-10-13
  • 1970-01-01
  • 2014-12-12
  • 1970-01-01
  • 2019-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多