error: expected expression before ‘{’ token in pthread rw_lock

error: expected expression before ‘{’ token in pthread rw_lock

所以我在某种数据结构中有一个节点的代码,并且该节点有一个读写锁 在使用 pthread_rwlock_t 之前初始化我使用 pthread_rwlock_init 的锁 rwlock = PTHREAD_RWLOCK_INITIALIZER;

事情是出于某种原因,它给出了一个错误,说它应该是 PTHREAD_RWLOCK_INITIALIZER 之前的一个表达式,我不明白它是什么,因为我知道我没有遗漏任何东西;

代码:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "state.h"
#include <pthread.h>

typedef struct inode_t {    
    type nodeType;
    union Data data;
    // ******************NEW ATTRIBUTE THAT INLCUDES THE LOCK *******************************
    pthread_rwlock_t lock;
} inode_t;

void inode_table_init() {
    for (int i = 0; i < INODE_TABLE_SIZE; i++) {
        inode_table[i].nodeType = T_NONE;
        inode_table[i].data.dirEntries = NULL;
        inode_table[i].data.fileContents = NULL;
        // ****************** NEW *******************************
        // Initializes the lock
        pthread_rwlock_init(&inode_table[i].lock ,NULL);
        inode_table[i].lock = PTHREAD_RWLOCK_INITIALIZER;
    }
}

int inode_create(type nType) {
    /* Used for testing synchronization speedup */
    insert_delay(DELAY);

    for (int inumber = 0; inumber < INODE_TABLE_SIZE; inumber++) {
        if (inode_table[inumber].nodeType == T_NONE) {
            inode_table[inumber].nodeType = nType;
            
            pthread_rwlock_init(&inode_table[inumber].lock ,NULL);
            inode_table[inumber].lock = PTHREAD_RWLOCK_INITIALIZER;

            if (nType == T_DIRECTORY) {
                /* Initializes entry table */
                inode_table[inumber].data.dirEntries = malloc(sizeof(DirEntry) * MAX_DIR_ENTRIES);
                
                for (int i = 0; i < MAX_DIR_ENTRIES; i++) {
                    inode_table[inumber].data.dirEntries[i].inumber = FREE_INODE;
                }
            }
            else {
                inode_table[inumber].data.fileContents = NULL;
            }
            return inumber;
        }
    }
    return FAIL;
}

好吧,函数做什么并不重要,重要的是我在初始化锁的行中有一个奇怪的错误

错误:

fs/state.c: In function ‘inode_table_init’:
fs/state.c:34:31: error: expected expression before ‘{’ token
         inode_table[i].lock = PTHREAD_RWLOCK_INITIALIZER;
                               ^
fs/state.c: In function ‘inode_create’:
fs/state.c:81:41: error: expected expression before ‘{’ token
             inode_table[inumber].lock = PTHREAD_RWLOCK_INITIALIZER;

好吧,我们将不胜感激。

您不需要这些作业。来自 POSIX 规范:

In cases where default read-write lock attributes are appropriate, the macro PTHREAD_RWLOCK_INITIALIZER can be used to initialise read-write locks that are statically allocated. The effect is equivalent to dynamic initialisation by a call to pthread_rwlock_init() with the parameter attr specified as NULL, except that no error checks are performed.

您只能在变量初始化中使用它,不能在赋值中使用。而且由于它等同于之前的线路调用,所以即使它有效也是多余的。