线程锁的问题 怎么都不明白 求高手指点一下!!!!!
有个跟多线程有关的题目 ,查了不少资料下面的代码不明白怎么回事。SEM *sem_init(int n) {
SEM *s;
s = (SEM *) malloc(sizeof(SEM));
if (s == NULL) {
perror("malloc");
exit(EXIT_FAILURE);
}
pthread_mutex_init(&s->m, NULL);
pthread_cond_init(&s->c, NULL);
s->s = n;
return s;
}
void P(SEM *s) {
pthread_mutex_lock(&s->m);
while (s->s < 1) {
pthread_cond_wait(&s->c, &s->m);
}
s->s--;
pthread_mutex_unlock(&s->m);
}
void V(SEM *s) {
pthread_mutex_lock(&s->m);
s->s++;
pthread_cond_broadcast(&s->c);
pthread_mutex_unlock(&s->m);
}
上面是3个函数
具体操作时:
b.writep = 0;
b.readp = 0;
b.sem_full = sem_init(0);
b.sem_free = sem_init(9);
pthread_mutex_init(&b.lock, NULL);
以及
P(b.sem_free);
b.socks[b.writep] = clsock;
b.writep = (b.writep + 1) % 9;
V(b.sem_full);
请问这样操作有什么好处 具体的意思到底是什么呢 ,我始终不理解。。。