互斥量实现线程同步问题
/*********************************************************************************//* 互斥量实现线程同步*//********************************************************************************/#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <pthread.h>struct foo{ int f_count; pthread_mutex_t f_lock; int data;};struct foo *foo_alloc(struct foo **fp) //分配信号空间{ //struct foo *fp; if ((*fp = (struct foo *)malloc(sizeof (struct foo))) != NULL) { (*fp)->f_count = 1; //计数初始化为1 (*fp)->data = 1; //数据为1 if (pthread_mutex_init(&(*fp)->f_lock, NULL) != 0) { free(*fp); return NULL; } } return *fp;}void foo_hold(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_destroy(&fp->f_lock); free(fp); } else { pthread_mutex_unlock(&fp->f_lock); }}void * fun(void * arg){ struct foo *p = (struct foo *)arg; foo_hold(p); printf("in pthread1: %d\n", p->data); p->data++; printf("in pthread1: %d\n", p->data); /************************************************问题??***********************************************************/ //foo_rele(p); //这里没有释放下一个进程怎么还怎么用啊? pthread_exit((void *)1 );}void * fun1(void * arg){ struct foo *p = (struct foo *)arg; foo_hold(p); printf("in pthread2: %d\n", p->data); p->data ++; printf("in pthread2: %d\n", p->data); foo_rele(p); pthread_exit((void *)1 );}int main(){ pthread_t tid1; pthread_t tid2; int err; struct foo *fp; foo_alloc(&fp); if ((err = pthread_create(&tid1, NULL, fun, (void *)fp)) != 0) { printf("pthread1 error!\n"); } if ((err = pthread_create(&tid2, NULL, fun1, (void *)fp)) != 0) { printf("pthread1 error!\n"); } //pthread_join(tid1, &p); //获取传递的参数并等待该子线程结束。 sleep(2); printf("in main pthread:\n"); return 0;}运行结果:[root@localhost work]# gcc 1.c -o 1 -lpthread[root@localhost work]# ./1in pthread1: 1in pthread1: 2in pthread2: 2in pthread2: 3in main pthread:[root@localhost work]#
//foo_rele(p); //这里没有释放下一个进程怎么还怎么用啊?
pthread_exit((void *)1 );
}
调用几次,它也不可能死锁,所以注释掉很随意。
[解决办法]
foo_hold里面不是lock又unlock里吗?
pthread_mutex_lock(&fp->f_lock);
fp->f_count ++;
pthread_mutex_unlock(&fp->f_lock);
已经解锁了啊。
foo_rele(p)只是释放资源啊