利用运行时函数的例子

  下面的例子采用运行时调用来完成π的计算

  PROGRAM pie
  IMPLICIT NONE
  INTEGER :: n,i,nnode,nthread,inode,counter
  INTEGER :: lck
  INTEGER, EXTERNAL :: omp_get_num_procs,omp_get_thread_num
  INTEGER, EXTERNAL :: omp_get_num_threads
  LOGICAL, EXTERNAL :: omp_test_lock
  REAL(8) :: w,x,sum,pi
  WRITE(6,'('' program pi running on columbus'')')
  nnode=omp_get_num_procs()
  WRITE(6,'('' number of processors = '',i2)')nnode
 ! read in number of strips
  WRITE(6,'('' enter number of strips to use for integration '')')
  READ(5,*)n
  w=1.0d0/REAL(n)
  sum=0.0d0
  WRITE(6,'('' enter number of threads to use '')')
  READ(5,*)nthread
  CALL omp_set_num_threads(nthread)
 ! create a pointer to a lock using variable lck
  CALL omp_init_lock(lck)
  counter=0
 ! $OMP parallel default(shared) private(i,x,inode) reduction(+:sum)
  nthread=omp_get_num_threads()
  WRITE(6,'('' num threads = '',i4)')nthread
  inode=omp_get_thread_num()
  WRITE(6,'('' hello world from '',i2)')inode
  DO WHILE(counter<n)
 ! spin loop waiting for lock
  DO WHILE(.NOT.omp_test_lock(lck))
  END DO
 ! got it
  counter=counter+1
  i=counter
 ! release lock
  CALL omp_unset_lock(lck)
 ! $OMP barrier
  WRITE(6,'('' thread '',i2,'' doing i= '',i4)')inode,i
  x=w*(REAL(i)-0.5d0)
  sum=sum+4.0d0/(1.0d0+x*x)
  END DO
 ! $OMP end parallel
  CALL omp_destroy_lock(lck)
  pi=w*sum
  WRITE(6,'('' pi = '',g17.10)')pi
  END PROGRAM pie

  需要注意的是,并不是所有的OpenMP编译器(运行时库)都提供这些接口,在这种情况下,用户可以直接调用Pthread的函数来完成相关的任务。