threads/mutex1.c 11-5#include <pthread.h> #include <stdlib.h> #include <apue.h>struct foo {int F_count; pthread_mutex_t F_lock; int f_id; /* ... more stuff here ... */};struct foo* foo_alloc (int id)/* Allocate the object */{foo* FP; if (fp = (foo*) malloc (sizeof)) = = NULL) {fp->f_count = 1; fp->f_id = ID; if (Pthread_mutex_init (&fp->f_lock, NULL)! = 0) {free (FP); return (NULL); }/* ... continue initialization ... */} return (FP);} void Foo_hold (foo *FP)/* Add a reference to the object */{Pthread_mutex_lock (&fp->f_lock); fp->f_count++; Pthread_mutex_unlock (&fp->f_lock);} void Foo_rele (foo* fp)/* Release a reference to the object */{Pthread_mutex_lock (&fp->f_lock); if (--fp->f_count = = 0) {/* Last reference */Pthread_mutex_unlock (&fp->f_lock); Pthread_mutex_destroy(&fp->f_lock); Free (FP); } else {pthread_mutex_unlock (&fp->f_lock); }}void* thr_fn (void* Arg) {printf ("New Thread:%lx\n", pthread_self ()); for (int i = 0; i < 90000000; i++) {Foo_hold (static_cast<foo*> (ARG)); } return ((void *) 8888);} int main () {pthread_t ntid; int err; void* ret; foo* PF = foo_alloc (1); Err = Pthread_create (&ntid, NULL, THR_FN, static_cast<void*> (PF)); if (0! = Err) {err_quit ("can ' t create thread:%s\n", strerror (err)); } printf ("Main thread:%lx\n", pthread_self ()); for (int i = 0; i < 90000000; i++) {Foo_hold (static_cast<foo*> (PF)); } err = Pthread_join (Ntid, &ret); if (err! = 0) {err_quit ("can ' t join with thread 1:%s\n", strerror (err)); } printf ("New Thread exit Code%d\n", (int) (long) ret); printf ("Pf->fcount =%d\n", pf->f_count); return 0;}
UNIX environment Advanced Programming 11.6 thread synchronization