- 论坛徽章:
- 0
|
apue中11.5例子- #include <stdlib.h>
- #include <pthread.h>
- struct foo {
- int f_count;
- pthread_mutex_t f_lock;
- /*...more stuff here ...*/
- };
- struct foo *
- foo_alloc(void) /* allocate the object */
- {
- struct foo *fp;
- int idx;
- if ((fp = malloc(sizeof(struct foo))) != NULL) {
- fp->f_count = 1;
- if (pthread_mutex_init(&fp->f_lock, NULL) != 0) {
- free(fp);
- return(NULL);
- }
- /* ... continue initialization ... */
- }
- return(fp);
- }
- void
- foo_hod(struct foo *fp)
- {
- pthread_mutex_lock(&fp->f_lock);
- fp->f_count++;
- pthread_mutex_unlock(&fp->f_lock);
- }
- void
- foo_rele(struct foo *fp)
- {
- pthread_mutex_lock(&fp->f_lock);
- if(--fp->f_count == 0) {
- pthread_mutex_unlock(&fp->f_lock);
- pthread_mutex_destroyk(&fp->f_lock);
- free(fp);
- } else {
- pthread_mutex_unlock(&fp->f_lock);
- }
- }
复制代码 当线程A调用了foo_rele后pthread_mutex_lock成功,假设此时fp->f_count == 1,
如果线程B在这个时候调用foo_hod阻塞在pthread_mutex_lock。
那么线程A之后的操作会free掉fp,线程B的操作不会有问题吗?? |
|