【发布时间】:2016-05-04 22:51:52
【问题描述】:
这是我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
sem_t s1, s2;
pthread_t foo_tid, bar_tid;
void *foo(void*) {
while(1) {
sem_wait(&s1);
printf("HI ");
sem_post(&s2);
}
}
void *bar(void*) {
while(1) {
sem_wait(&s2);
printf("HO ");
sem_post(&s1);
}
}
int main() {
sem_init(&s1, 0, 0);
sem_getvalue(&s1, &foo_tid);
sem_init(&s2, 0, 0);
sem_getvalue(&s2, &bar_tid);
pthread_create(&foo_tid, NULL, foo, NULL);
pthread_create(&bar_tid, NULL, bar, NULL);
return 0;
}
我正在尝试获取信号量 s1 和 s2 的输出。但我不断收到这些错误:
sema.c: In function 'main':
sema.c:29:3: warning: passing argument 2 of 'sem_getvalue' from incompatible pointer type [enabled by default]
In file included from sema.c:6:0:
/usr/include/semaphore.h:72:12: note: expected 'int * __restrict__' but argument is of type 'pthread_t *'
sema.c:31:3: warning: passing argument 2 of 'sem_getvalue' from incompatible pointer type [enabled by default]
In file included from sema.c:6:0:
/usr/include/semaphore.h:72:12: note: expected 'int * __restrict__' but argument is of type 'pthread_t *'`
我只是无法摆脱这个错误。如果有人能帮我解决这个问题,将不胜感激!
【问题讨论】:
-
你读过
sem_getvalueman page吗?它告诉你它的参数类型需要是什么,你给了它什么?此外,阅读警告消息会直接告诉您“预期..但参数是..”吗? -
你得到了一个清晰的,(或可以预期的一样清晰:),编译器错误消息,抱怨'sem_getvalue'的第二个参数类型不匹配。发生这种情况是因为“sem_getvalue”的第二个参数类型不匹配。
-
删除
sem_getvalue调用。它们没有使用的目的。当pthread_create被调用时,它not 取消引用reading 的值。它只使用指针来设置返回时的 tid 值(即)在调用之前设置的值被忽略[和替换]。此外,因为sem_init在sem_getvalue之前完成,所以该值将始终为零。