- 论坛徽章:
- 0
|
本帖最后由 apueunix 于 2013-09-30 11:32 编辑
先谢谢,
apue 互斥量foo_find例子不解,对f_id查询前为什么结构数据不加锁(下面红色部分)?如果其它线程直接修改f_id的话,f_id 数据就不致;还是说f_id是不会修改的,但是从结构数据的保护上也要控制吧;
#include <stdlib.h>
#include <pthread.h>
#define NHASH 29
#define HASH(fp) (((unsigned long)fp)%NHASH)
struct foo *fh[NHASH];
pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER;
struct foo {
int f_count;
pthread_mutex_t f_lock;
struct foo *f_next;
int f_id;
/* ... 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);
}
idx = HASH(fp);
pthread_mutex_lock(&hashlock);
fp->f_next = fh[idx];
fh[idx] = fp;
pthread_mutex_lock(&fp->f_lock);
pthread_mutex_unlock(&hashlock);
/* ... continue initialization ... */
}
return(fp);
}
struct foo *fp
foo_find( int id)
{
struct foo *fp;
int idx;
idx = HASH(fp);
pthread_mutex_lock(&hashlock);
for ( fp=fp[idx]; fp !=NULL;fp=fp[idx]->f_next)
{
if (fp ->f_id == id)
{
fp->f_count++;
break;
}
}
pthread_mutex_unlock(&hashlock);
return (fp);
}
................. 后续省略
|
|