首先是一个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))+...)