标签:
// 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(foo))) != 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; }
标签:
原文地址:http://www.cnblogs.com/sunyongjie1984/p/4279122.html