c - 正确使用结构数组

标签 c arrays struct

我正在开发一个程序,该程序使用线程充当尝试入住、使用和退房酒店的客人。

为了跨所有线程跟踪 guest 数据,我使用了一个struct:

struct thread_data
{
    int guest_id;   // id number of guest
    int room;       // room guest utilizes
    int event;      // 0=swim, 1=resturaunt, 2=fitness, 3=business
    int cost;       // final cost of stay (random value)
}

由于会有多个客人使用酒店,我尝试创建一个客人结构数组:

struct thread_data thread_data_array[NUM_GUESTS]; // array initialization

问题 1:这是否正确创建了 struct 类型的数组?数组的名称是thread_data_array吗?


此外,我有我的 Guest() 方法,在该方法中我尝试从该 struct 获取和设置数据:

void *Guest(void *guestData)
{
    int guestid, guestroom, gevent, gcost;
    struct thread_data *guest_data;

    guestroom = guest_data->room;

    gevent = getRandomLessThan(4);  // activity connected to 0, 1, 2, 3
    guest_data[guestid].event = gevent; // assign to Guest's struct
}

问题 2:我是否正确地从我的结构中“获取”和“设置”?


简而言之,我对我的三个部分的正确命名有点困惑:

结构:struct thread_data;

数组:struct thread_data thread_data_array[NUM_GUESTS];

在 Main() 中:struct thread_data *guest_data;


这是我的整个程序,包括所有错误:

//Hotel Project 
//This project creates a system to simulate a hotel.

#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define NUM_GUESTS  10 //10 guests

void *CheckIn(void *); // the two threads
void *CheckOut(void *);

pthread_t guests[NUM_GUESTS];

sem_t roomSem;              //total number of rooms in the hotel
sem_t check_in, check_out;  //reception desks
sem_t s1, s2, s3, s4, s5;   //global semaphores

int rooms[5];   //keep track of availability of each room

int total_guests;       //incremented with each guest check-out
int pool;               //incremented with each guest use pool
int resturant;          //incremented with each guest use resturant
int fitness_center;     //incremented with each guest use fitness center
int business_center;    //incremented with each guest use business center

struct thread_data
{
    int guest_id;   // id number of guest
    int room;       // room guest utilizes
    int event;      // 0=swim, 1=resturaunt, 2=fitness, 3=business
    int cost;       // final cost of stay (random value)
}

struct thread_data thread_data_array[NUM_GUESTS]; // array initialization


void *Guest(void *guestData)
{
int guestNumber = *(int *) guestData; //error?
int guestid, guestroom, gevent, gcost;
struct thread_data *guest_data;

guestid = (struct int) guestData; //error?

//guest_data = (struct thread_data *) guestData;
//guestid = guest_data->guest_id; // guestID stored in the struct

/*output*/ printf("Guest %d waits for room to be available\n", guestid);
sem_wait(&roomSem); // guest wants a room; check to see if one is available

/*output*/ printf("Guest %d waits for check-in\n", guestid);
sem_wait(&check_in); // if there is a room available, guest approaches check_in clerk; making him busy
/*output*/ printf("Guest %d goes to the check-in reservationist\n", guestid);
CheckIn(thread_data_array[guestid]); //check in
sem_post(&s1); // event ordering

sem_wait(&s2);
guestroom = guest_data->room;
/*output*/ printf("Guest %d receives Room %d and completes check-in\n", guestid, room);

sem_post(&check_in); // event ordering. Check-In now available

gevent = getRandomLessThan(4);  // activity connected to 0, 1, 2, 3
guest_data[guestid].event = gevent; // assign to Guest's struct

switch(gevent)
{
    case(0): /*output*/ printf("Guest %d does event: Pool\n", guestid);
            pool++;

    case(1): /*output*/ printf("Guest %d does event: Resturant\n", guestid);
            resturant++;

    case(2): /*output*/ printf("Guest %d does event: Fitness Center\n", guestid);
            fitness_center++;

    case(3): /*output*/ printf("Guest %d does event: Business Center\n", guestid);
            business_center++;
}
/*output*/ printf("Guest %d does event: %d\n", guestid, gevent);

sleep(getRandomLessThan(5) - 1); // sleep for 1 to 3 seconds

gcost = getRandomLessThan(300);     // 0 < cost < 300
guest_data[guestid].cost = gcost;   // maybe should be in CheckOut
//thread_data_array[guest].cost = money;

sem_wait(&check_out); // guest waits for check-out desk to be available
/*output*/ printf("Guest %d goes to the check-out reservationist and returns room %d\n", guestid, room);
sem_post(&s3); // event ordering

printf("Main: Creating CheckOut thread %d", guestid);
rc = pthread_create(&guest[guestid], NULL, CheckOut, (void *)&thread_data_array[guest]);
if (rc){
    printf("ERROR1; return code from pthread_create() is %d\n", rc);
    exit(-1);
}

sem_wait(&s4); // event ordering
total = thread_data_array[guestid].cost;
/*output*/ printf("Guest %d receives the total balance of $%d\n", guestid, total);
/*output*/ printf("Guest %d makes a payment\n", guestid);
total_guests++;
sem_post(&s5); // event ordering

}

int getRandomLessThan(int x)
{
    srand(time(NULL));
    int r = rand() % x;
    printf("Random number: %d\n", r);

    return r;
}

int GetOpenRoom()
{
    for (int i=0; i<rooms.length; i++)
    {
        if (rooms[i] = 1) // room vacant
        {
            rooms[i] = 0; // mark as filled
            return i;
        }
    }
}

void *CheckIn(void *guestData)
{
int guestid, guestroom;
struct thread_data *guest_data;
guest_data = (struct thread_data *) guestData;

guestid = guest_data->guest_id; // guestID stored in the struct
/**/guestroom = guest_data->room; // room stored in the struct
/**/printf("Guestroom: %d", guestroom); // expecting NULL

sem_wait(&s1); // event ordering

/*output*/ printf("The check-in reservationist greets Guest %d\n", guestid);
sem_wait(&roomSem); // use a room
guestroom = GetOpenRoom();
guest_data[guestid].room = guestroom; // mark room number in guest's struct
//thread_data_array[guestid].room = guestroom;
//which do i need?

/*output*/ printf("Assign room %d to Guest %d\n", guestroom, guestid);

sem_post(&s2); // event ordering

pthread_exit(NULL);
}


void *CheckOut(void *guestData)
{
int guestid, guestroom, guestcost;
struct thread_data *guest_data;

guest_data = (struct thread_data *) guestData;
guestid = guest_data->guest_id; // guestID stored in the struct
guestroom = guest_data->room; // room stored in the struct
guestcost = guest_data->cost; // cost stored in the struct

sem_wait(&s3); // event ordering
/*output*/ printf("The check-out greets Guest %d and receives the key from room %d\n", guestid, guestroom);
rooms[guestroom] = 1; // room now available, set back to 1
sem_post(&roomSem); // release a room
/*output*/ printf("Calculate the balance for Guest %d\n", guestid);
//case situation for each event. makes guestcost= different value for each event
thread_data_array[guestid].cost = guestcost;
sem_post(&s4); // event ordering
sem_wait(&s5); // event ordering
/*output*/ printf("Receive $%d from Guest %d and complete the check-out\n", cost, guestid);

pthread_exit(NULL);
}



//Guest
int main (int argc, char *argv[])
{
pthread_t desk[2];
int rc;
int guest;
struct thread_data *guest_data;

sem_init(&roomSem, 1, 5); //not 0 means shared between multiple processes, 5 is initial value
sem_init(&check_in, 1, 1);
sem_init(&check_out, 1, 1);
sem_init(&s1, 1, 0);
sem_init(&s2, 1, 0);
sem_init(&s3, 1, 0);
sem_init(&s4, 1, 0);
sem_init(&s5, 1, 0);

rooms[5] = {1,1,1,1,1};

pthread_create(&desk[0], NULL, CheckIn, NULL);  // Check In runs on it's own now
pthread_create(&desk[1], NULL, CheckOut, NULL); // Check Out runs on it's own now

for(guest = 0; guest < NUM_GUESTS; guest++)
{
    int *guestNumber = malloc(sizeof(*guestNumber);
    guestNumber = guest;
    //thread_data_array[guest].guest_id = guest; // guest ID for each guest thread
    rc = pthread_create(guests[guest], NULL, Guest, guestNumber); //Guest method, guest argument
    //Guest only takes a void argument. Must use thread_data_array?
    if (rc) {
        printf("ERROR; return code from pthread_create(Guest) is %d\n", rc);
        exit(-1);
    }
}

printf("\t\t\tNumber of Customers\n");
printf("Total Guests:\t%d\n", total_guests);
printf("Pool:\t%d\n", pool);
printf("Resturant:\t%d\n", resturant);
printf("Fitness Center:\t%d\n", fitness_center);
printf("Business Center:\t%d\n", business_center);

sem_close(&roomSem);
sem_close(&check_in);
sem_close(&check_out);
sem_close(&s1);
sem_close(&s2);
sem_close(&s3);
sem_close(&s4);
sem_close(&s5);

pthread_exit(NULL);
}

编辑:我在线程中使用空指针作为参数,因为我使用的是 pthread_create()

最佳答案

问题 1:

是的,struct thread_data thread_data_array[NUM_GUESTS];正在创建 thread_data_array作为 NUM_GUESTS 的数组类型元素 struct thread_data .

问题 2:

guest_data是指向您的结构的指针,但未初始化(指向任何地方):

struct thread_data *guest_data;

guestroom = guest_data->room;

关于c - 正确使用结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36874809/

相关文章:

C 程序显示最多输入的 %2==0 个数字,直到您输入数字 %2!=0 && %7==0

c++ - 被调用者分配被调用者释放

javascript - 使数组中的数字相对于 0 - 100

用于更改数组的 "order"的 PHP 算法

c - 将 char 分配给一个结构内的字符数组,该结构位于结构数组内,结构数组位于结构数组内

c - 指向存储在结构中的数组的指针

c - 使用 strtok 吐出数组并将标记存储在唯一的以 null 结尾的字符串中

c - 哪种代码更简洁、设计更好?

c++ - 运行时检查失败 #2 - 变量 "primes"周围的堆栈已损坏

c - 将多个值从 shell 脚本返回到 c 程序