介绍忙等待,互斥量,信号量,条件变量:以估计π为例(并行计算,用Pthread库)

首先是一个hellowerld程序,创建多个线程并打印语句,主要是想说明这三个函数:

int pthread_create(pthread_t* thread,const pthread_attr_t* attr,void* fuc,void* arg);//创建线程并关联运行函数

int pthread_join(pthread_t* thread, void **retval);//等待其他线程结束,这里的结束也意味着内存空间的释放

free(pthread_t* )//手动释放程序分配的空间,如malloc()

下面是代码(gcc -g -Wall -o helloworld heloworld.c -lpthread ; ./helloworld):

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
/*

   int pthread_create(pthread_t* thread,const pthread_attr_t* attr,void* fuc,void* arg);

   int pthread_join(pthread_t* thread, void **retval);

*/

//thread's num
int thread_count;

void *Hello(void* rank);

int main(int argc,char* argv[]){
	//Use long in case of 64-bit system
	long thread;
	pthread_t* thread_handles;

	//Get number of threads from command line
	thread_count = strtol(argv[1],NULL,10);
	thread_handles = malloc(thread_count*sizeof(pthread_t));

	for(thread = 0;thread < thread_count;thread++){
        //Create threads
		pthread_create(&thread_handles[thread],NULL,Hello,(void*)thread);
	}
	printf("Hello from the main thread\n");

	for(thread = 0;thread < thread_count;thread++){
        //Wait util thread_handles[thread] complete
		pthread_join(thread_handles[thread],NULL);
	}
	free(thread_handles);
	return 0;
}//main

void *Hello(void *rank){
	long my_rank=(long)rank;
	printf("Hello from thread %ld of %d\n",my_rank,thread_count);
	return NULL;
}//Hello

熟悉了基本的代码(Hello函数可以被你想让线程执行的函数所替代)了之后,来看用并行的方法来估计π的大小。

公式是这样的:pi=4(1-1/3+1/5-1/7+...+((-1)^n)*(1/(2n+1))+...)

我们用多个线程来处理这些计算,每个线程处理一部分。把所有计算都加起来,就是π的值了。

这就涉及到一个问题了,假设变量sum为全局变量,那么多个线程对它(临界区)进行修改的时候,会产生覆盖的情况。

下面我分别用忙等待,互斥量,信号量来解决临界区问题。

/

忙等待:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
/*
   pi=4(1-1/3+1/5-1/7+...+((-1)^n)*(1/(2n+1))+...)

   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值