c - ' {' 之前的预期表达式与互斥体初始化

标签 c struct pthreads

我正在尝试在函数内初始化互斥体数组和条件变量。 该数组是我定义的 Cell 类型,每个 Cell 包含互斥锁、条件变量和字符。 我在 intiail_circle 的 for 循环内的 3 行中收到错误:

expected expression before ‘{’ token.

我也尝试在函数外初始化数组,但没有用。任何想法是什么原因造成的?

代码:

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 5    
#define num_of_cells  (2*(2*N - 2))


typedef struct Generator{
    pthread_t tid;
    int id;
}Genarator;

typedef struct Car{
    pthread_t carId;
    int location ,GenID,num_of_steps;
}Car;

typedef struct Cell{
    char val;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
}Cell;

Cell circle[num_of_cells];
Cell generators_location[4];
struct Generator *generators[4];

int main(){
    initial_circle();
}

void initial_circle(){
    int i;
    for(i = 0; i < num_of_cells; i++){
        circle[i].mutex = PTHREAD_MUTEX_INITIALIZER;
        circle[i].cond = PTHREAD_COND_INITIALIZER;
        circle[i].val = ' ';
    }
}

最佳答案

PTHREAD_MUTEX_INITIALIZERPTHREAD_COND_INITIALIZERstruct 的初始化器。它们看起来像这样:

#define PTHREAD_COND_INITIALIZER { { 0, 0, 0, 0, 0, (void *) 0, 0, 0 } }
#define PTHREAD_MUTEX_INITIALIZER { { 0, 0, 0, 0, 0, __PTHREAD_SPINS, { 0, 0 } } }

此语法仅在初始化程序中有效,在赋值时无效,这就是您收到错误的原因。

你可以通过从它们中创建一个复合文字来解决这个问题:

    circle[i].mutex = (pthread_mutex_t)PTHREAD_MUTEX_INITIALIZER;
    circle[i].cond = (pthread_cond_t)PTHREAD_COND_INITIALIZER;

此外,您在函数 initial_circle 声明之前调用它。您应该在文件中将 initial_circle 的定义移到 main 之前:

void initial_circle(){
    ...
}

int main(){
    initial_circle();
}

关于c - ' {' 之前的预期表达式与互斥体初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56004874/

相关文章:

c - 使用 dup() 创建重复文件描述符和创建硬链接(hard link)之间的区别?

c - 在 win32/C/C++ 中共享内存和 IPC 的最快进程技术

c - 初学者从结构数组中删除第一个元素 (C)

string - Swift nil 可选字符串 = 空字符串

php - 在 MAMP 3.0.2 上启用 ZTS

c - 如何将 float 转换为不带零和点的 float

c - 使用 C 在 Windows API 中构建时间表

c - 如何在 C 应用程序中处理冲突的结构定义

c - pthread 函数的参数可以是另一个函数?

c++ - Pthread 模板参数错误