【问题标题】:Error initializing SIMPLEQ_HEAD in C在 C 中初始化 SIMPLEQ_HEAD 时出错
【发布时间】: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条件变量semaphoremutex 简单得多,并且已经在 POSIX 中可用。 (sem_t,见sem_init(3)
  • @FelixPalmen 这是我的操作系统课程,所以我们正在学习自己实现它。
  • 另外,C 中并没有真正的“类”。你的 semaphore_t 在概念上可以被认为是一个“类”,因为你有一个 create “方法”和一堆方法接受一个 this 指针 作为第一个参数,但在 C 的上下文中,它仍然不是一个类,因为 C 不知道这样的事情。
  • @szczurcio 谢谢 :) 我会调查的

标签: c queue pthreads semaphore


【解决方案1】:

经过一番测试,我意识到了

sem->head = SIMPLEQ_HEAD_INITIALIZER( sem->head );

是一个 静态 操作,所以它不会工作,因为我正在动态创建信号量/SIMPLEQ。

我把那行改为

SIMPLEQ_INIT( &(sem->head) ); // note that you don't set anything equal to the result

它动态处理初始化,并解决了我的问题。

【讨论】:

    猜你喜欢
    • 2012-04-03
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-25
    • 1970-01-01
    相关资源
    最近更新 更多