【发布时间】:2015-10-31 19:58:56
【问题描述】:
我正在尝试在 C 中初始化 SIMPLEQ_HEAD 并收到以下错误:
# gcc -o semaphore semaphore.c
semaphore.c: In function `createSemaphore':
semaphore.c:10: syntax error before `{'
我的 semaphore.c 类看起来像:
#include <stdio.h>
#include "semaphore.h"
semaphore_t* createSemaphore( int initialCount )
{
semaphore_t* sem;
sem = (semaphore_t *) malloc( sizeof( semaphore_t ) );
sem->head = SIMPLEQ_HEAD_INITIALIZER( sem->head );
sem->count = initialCount; // set the semaphores initial count
return sem;
}
...
int main()
{
semaphore_t* my_semaphore = createSemaphore( 5 );
return 0;
}
我的 semaphore.h 看起来像:
#ifndef SEMAPHORE_H
#define SEMAPHORE_H
#include <sys/queue.h>
#include <pthread.h>
#include <stdlib.h>
struct entry_thread {
int threadid;
SIMPLEQ_ENTRY(entry_thread) next;
} *np;
struct semaphore {
int count;
pthread_mutex_t mutex;
pthread_cond_t flag;
SIMPLEQ_HEAD(queuehead, entry_thread) head;
};
typedef struct semaphore semaphore_t;
semaphore_t* createSemaphore( int initialCount );
void destroySemaphore( semaphore_t* sem );
void down( semaphore_t* sem );
void up( semaphore_t* sem );
#endif
我是 C 新手并使用 SIMPLEQ,所以如果有人对此有经验,我将不胜感激。
供您参考,SIMPLEQ_HEAD 的手册页是:http://www.manualpages.de/OpenBSD/OpenBSD-5.0/man3/SIMPLEQ_HEAD.3.html
【问题讨论】:
-
我没有全部读完,但是让我一头雾水:为什么要在 mutexes 之上实现 semaphore 和条件变量? semaphore 比 mutex 简单得多,并且已经在 POSIX 中可用。 (
sem_t,见sem_init(3)) -
@FelixPalmen 这是我的操作系统课程,所以我们正在学习自己实现它。
-
另外,C 中并没有真正的“类”。你的
semaphore_t在概念上可以被认为是一个“类”,因为你有一个 create “方法”和一堆方法接受一个 this 指针 作为第一个参数,但在 C 的上下文中,它仍然不是一个类,因为 C 不知道这样的事情。 -
@szczurcio 谢谢 :) 我会调查的
标签: c queue pthreads semaphore