24.05.2014 Views

XL Fortran Enterprise Edition for AIX : User's Guide - IBM

XL Fortran Enterprise Edition for AIX : User's Guide - IBM

XL Fortran Enterprise Edition for AIX : User's Guide - IBM

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

!*****************************************************************<br />

use, intrinsic::f_pthread<br />

integer(4) ret_val<br />

type(f_pthread_mutex_t) mutex<br />

type(f_pthread_cond_t) cond<br />

pointer(p, byte)<br />

! Initialize mutex and condition variables be<strong>for</strong>e using them.<br />

! For global variables this should be done in a module, so that they<br />

! can be used by all threads. If they are local, other threads<br />

! will not see them. Furthermore, they must be managed carefully<br />

! (<strong>for</strong> example, destroy them be<strong>for</strong>e returning, to avoid dangling and<br />

! undefined objects).<br />

mutex = PTHREAD_MUTEX_INITIALIZER<br />

cond = PTHREAD_COND_INITIALIZER<br />

......<br />

! Doing something<br />

......<br />

! This thread needs to allocate some memory area used to<br />

! synchronize with other threads. However, when it waits on a<br />

! condition variable, this thread may be canceled by another<br />

! thread. The allocated memory may be lost if no measures are<br />

! taken in advance. This will cause memory leakage.<br />

ret_val = f_pthread_mutex_lock(mutex)<br />

p = malloc(%val(4096))<br />

! Check condition. If it is not true, wait <strong>for</strong> it.<br />

! This should be a loop.<br />

! Since memory has been allocated, cleanup must be registered<br />

! <strong>for</strong> safety during condition waiting.<br />

ret_val = f_pthread_cleanup_push(mycleanup, FLAG_DEFAULT, p)<br />

ret_val = f_pthread_cond_wait(cond, mutex)<br />

! If this thread returns from condition waiting, the cleanup<br />

! should be de-registered.<br />

call f_pthread_cleanup_pop(0) ! not execute<br />

ret_val = f_pthread_mutex_unlock(mutex)<br />

! This thread will take care of p <strong>for</strong> the rest of its life.<br />

......<br />

! mycleanup looks like:<br />

subroutine mycleanup(passed_in)<br />

pointer(passed_in, byte)<br />

external free<br />

call free(%val(passed_in))<br />

end subroutine mycleanup<br />

410 <strong>XL</strong> <strong>Fortran</strong> <strong>Enterprise</strong> <strong>Edition</strong> <strong>for</strong> <strong>AIX</strong> : User’s <strong>Guide</strong>

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!