【问题标题】:Output of semaphore values信号量值的输出
【发布时间】: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;
}

我正在尝试获取信号量 s1s2 的输出。但我不断收到这些错误:

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_getvalue man page吗?它告诉你它的参数类型需要是什么,你给了它什么?此外,阅读警告消息会直接告诉您“预期..但参数是..”吗?
  • 你得到了一个清晰的,(或可以预期的一样清晰:),编译器错误消息,抱怨'sem_getvalue'的第二个参数类型不匹配。发生这种情况是因为“sem_getvalue”的第二个参数类型不匹配。
  • 删除sem_getvalue 调用。它们没有使用的目的。当pthread_create 被调用时,它not 取消引用reading 的值。它只使用指针来设置返回时的 tid 值(即)在调用之前设置的值被忽略[和替换]。此外,因为sem_initsem_getvalue 之前完成,所以该值将始终为零。

标签: c semaphore


【解决方案1】:

来自sem_getvalue,值应该是 int :

声明int s1_val, s2_val;

  sem_init(&s1, 0, 0);
  sem_getvalue(&s1, &s1_val);
  sem_init(&s2, 0, 0);
  sem_getvalue(&s2, &s2_val);

【讨论】:

  • 将其更改为 int 会出现另一个错误,对于 pthread_create
【解决方案2】:

第二个参数应该是一个指向int 的指针,当你传入pthread_t 的地址时。 pthread_t 不是您系统上的 int

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多