⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pi.c

📁 linux下多线程实现生产者消费者及用并行算法求圆周率等经典算法
💻 C
字号:
/* Parallel C code to demonstrate Linux thread interface *//* Algorithm appears to be based on the series expansion of arctan(pi/4) */#include <stdio.h>#include <stdlib.h>#include <pthread.h>volatile double pi = 0.0;  /* Approximation to pi (shared) */pthread_mutex_t pi_lock;   /* Lock for above */volatile double intervals; /* How many intervals? */void *process(void *arg){	register double width, localsum;	register int i;	register int iproc = (*((char *) arg) - '0');	/* Set width */	width = 1.0 / intervals;	/* Do the local computations */	localsum = 0;	for (i=iproc; i<intervals; i+=2) 	{		register double x = (i + 0.5) * width;		localsum += 4.0 / (1.0 + x * x);	}	localsum *= width;	/* Lock pi for update, update it, and unlock */	pthread_mutex_lock(&pi_lock);	pi += localsum;	pthread_mutex_unlock(&pi_lock);	return(NULL);}int main(int argc, char **argv){	pthread_t thread0, thread1;	void * retval;	/* Get the number of intervals */	intervals = atoi(argv[1]);	/* Initialize the lock on pi */	pthread_mutex_init(&pi_lock, NULL);	/* Make the two threads */	pthread_create(&thread0, NULL, process, "0");	pthread_create(&thread1, NULL, process, "1");	/* Join (collapse) the two threads */	pthread_join(thread0, &retval);	pthread_join(thread1, &retval);	/* Print the result */	printf("Estimation of pi is %20.18f\n", pi);	return 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -