如何在整个程序中访问有关线程的信息

时间:2013-10-06 02:15:45

标签: c++ c multithreading

问题1:我正在尝试命名每个线程,以便它可以在整个程序中使用,但是我收到的错误如“在'plane [t]'中请求成员'fid'这是非类型'pthread_t'它指的是使用plane [t] .tid或使用plane [t] .startState。我不知道如何为每个单独的线程获取/保存这些值。

问题2:一旦我有一个线程的startState,我怎样才能将线程发送到takeoff()函数(一系列开关状态和printfs)。

问题3:什么应该传递到StartState函数?我试图让每个线程记住它的开始状态,以便稍后在代码中我可以让一个航班“着陆”或“起飞”。

以下是相关代码:在10月10日22:37更新

#include <pthread.h>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <queue>
#include <unistd.h>
#include <algorithm>
#include <time.h>
#include <ctime> 

#define NUM_THREADS 3       //3 flights

using std::queue;
using std::vector; 

pthread_mutex_t runway1lock;
pthread_mutex_t runway2lock;

bool run1occupied;
bool run2occupied;

struct flight_data{                 //each plane has these characteristics
        //void *FlightID;
    long fid;
        int startState;        // if start=1 ==> taking off    :::     if start=2 ==> landing
        int flyTime;            //fly == randomly generated time (order) of takeoff/land                
};

struct flight_data flightinfo[NUM_THREADS];

void *FlightID(void *flightid){
        struct flight_data *my_flights;
        my_flights = (struct flight_data*)flightid;
        int taskid;
        taskid = my_flights->fid;
 //       long fid;
  //      fid = (long)flightid;
//      printf("Flight #%1d\n", tid);
        pthread_exit(NULL);
}

void Start(struct flight_data my_flights){
        my_flights = (struct flight_data)my_flights;
        int startState;
    srand(time(0));
    my_flights.startState = rand() % 2+1;
        std::string startstring;
        if(my_flights.startState == 1){
                startstring = "Taking off";
        }
        if(my_flights.startState == 2){
                startstring = "Landing";
        }
    for(int i = 1; i<NUM_THREADS+1; i++){
            std::cout << "Start state for Flight # " << i << " is " << startstring << std::endl;
    }
}

void takeoff(struct flight_data my_flights){
    my_flights = (struct flight_data)my_flights;    
    for(int i = 1; i<NUM_THREADS+1; i++){
        int state = my_flights.startState;
        switch(state){  
            case 1:{        //G (GATE)
                std::cout << "Flight # " << flightinfo[i].fid << " is listed as waiting at the gate." << std::endl; 
                std::cout << "Flight # " << flightinfo[i].fid << "'s position in queue for runway: " << flightinfo[i].flyTime << std::endl; 
                sleep(3);
                state = 2;
                break;
            }   
            case 2: {       //Q (queue) -- sets order for use of runway
                queue<pthread_t> queue;
                vector<int> flightTimes;    
                int soonestFlightTime = 10;
                flightTimes.push_back(flightinfo[i].flyTime);           //put all flight times into a vector called flightTimes
                std::sort(flightTimes.begin(), flightTimes.end());      //sort the vector of flightTimes low to high
                std::reverse(flightTimes.begin(), flightTimes.end());       //flips vector -- high(front) to low(back)
                while(!flightTimes.empty()){
                    if (flightinfo[i].flyTime == flightTimes.back()){   //if a thread has the soonest flight time   
                        queue.push(i);      //then put the flight in the runway queue
                        flightTimes.pop_back();     //pop off the soonest flight time 
                    }
                }   
                while(!queue.empty()){
                    if(flightinfo[i].fid == queue.front()){
                        state = 3;
                        queue.pop();
                        sleep(3);
                    }   
                }
                break;
            }
            case 3: {       //CLR (clearance for runway)
                std::cout << "Flight # " << flightinfo[i].fid << " has clearance to move to the runway." << std::endl;  //will go in order of queue
                if(run1occupied){
                    sleep(3);
                }
            //  else if(collide){
            //      state = 7;
            //  }
                else{
                    state = 4;
                }
                break;      
            }
            case 4: {       //RTO (runway takeoff)
                pthread_mutex_lock(&runway1lock);
                run1occupied = true;
                std::cout << "Flight # " << flightinfo[i].fid << " is taking off. Runway occupied. Stand by." << std::endl;
                sleep(3);
                pthread_mutex_unlock(&runway1lock);
                run1occupied = false;
                state = 5;
                break;
            }
            case 5: {       //CZ (cruise)
                std::cout << "Flight # " << flightinfo[i].fid << " is reaching proper altitude and cruising toward destination." << std::endl; 
                sleep(3);
            //  if(!collide){
                    state = 6;
            //  }
            //  else{
            //      state = 7;  //collision!!!
            //  }
                break;
            }
            case 6: {       //RMV (remove from monitoring list)
                std::cout << "Flight # " << flightinfo[i].fid << " has been removed from the monitoring list." << std::endl;
                break; 
            }       
            case 7:{        //COLL (collision)
                std::cout << "Collision in the air. There were many casualties." << std::endl;
                break;
            }
        }
    }
}

void landing(struct flight_data my_flights){
    my_flights = (struct flight_data)my_flights;
    for (int i = 0; i<NUM_THREADS; i++){
        int state = my_flights.startState;
        switch(state){
            case 1:{        //ENTR (enter monitoring list)
                state = 2;
                break;
            }
            case 2:{        //Q (queue)
                //if not the first thing in the queue then state = 4;
                //otherwise state = 3;
            }
            case 3:{        //RWL (runway land)
                state = 5;
                break;
            }
            case 4:{        //HVR (hover)
                //if first in queue then state = 3;
                //otherwise stay here
                //if collision state = 7;
            }
            case 5:{        //CLR (clearance to move to gate)
                //if collision state = 7
                //otherwise state = 6;
            }
            case 6:{        //G (gate)

            }
            case 7:{        //COLL (collision)

            }
        }
    }
}

/*
bool collision(){
    bool collide;
    //random
    if(){
        collide = true;
    }
    else{
        collide = false;
    }
    return collide;
}*/

int main(int argc, char *argv[]){
        pthread_t flights[NUM_THREADS];         //pthread_t keeps a thread ID after the thread is created with pthread_create()
                                                //it's like an index on a vector of threads
        int *taskids[NUM_THREADS];
        int rc;
        long t;
        for (t=1; t<=NUM_THREADS; t++){                                 //loop creates threads(flights)
                printf("In main: Creating flight %1d\n", t);
                flightinfo[t].fid= t;
                rc = pthread_create(&flights[t], NULL, FlightID, (void *)&flights[t]);
                if (rc){
                        printf("ERROR: return code from pthread_create() is %d\n", rc);
                        return (-1);
                }
                printf("Created flight %1d\n", t);
        //      Start(flightinfo[t]);
                flightinfo[t].startState = rand() % 2+1;
                std::cout << flightinfo[t].startState << std::endl;
                if((flightinfo[t].startState)==1){
                        std::cout << "Flight # " << flightinfo[t].fid << " is listed with start state as " << flightinfo[t].startState << std::endl;
                        takeoff(flightinfo[t]);
                        //go to takeoff function and go through switch case     
                }
                if((flightinfo[t].startState)==2){
                        std::cout << "Flight # " << flightinfo[t].fid << " is listed with start state as " << flightinfo[t].startState << std::endl;
                        landing(flightinfo[t]);
                        //go to landing function and go through switch case     
                }
        }
        pthread_exit(NULL);
}

2 个答案:

答案 0 :(得分:1)

您似乎将pthread_t管理变量planes与包含航班数据flights的变量混淆。

pthread库使用pthread_t管理变量planes,你应该只将它用作pthread库调用的参数,否则只需不管它而不用担心它。将变量planes视为您创建的存储区域,然后将其提供给pthread库以供使用,并通过这样做将该变量的所有权授予pthread库。

因此,业务的第一个顺序是将pthread管理与线程操纵的实际数据之间的区别分开并区别开来。

您有几个地方使用pthread管理变量planes,就像它是一个飞行数据变量一样。它不是。将planes替换为flights

        if((flights[t].startState)==1){
                std::cout << "Flight # " << flights[t].fid << " is listed as waiting at the gate." << std::endl;
                void takeoff();
                //go to takeoff function and go through switch case     
        }
        if((flights[t].startState)==2){
                std::cout << "Flight # " << flights[t].fid << " is listed as waiting to land." << std::endl;
                //go to landing function and go through switch case     
        }

函数StartState()中的这一点来源没有意义。

for(int i = 0; i<NUM_THREADS; i++){
        startState = rand() % 1+2;
}
startState = my_flights->startState;

我想你想要设置一个随机启动状态的特定航班的起始状态。因此我希望源代码如下所示,因为我假设您有兴趣设置特定航班的起始状态,并且除了运行随机数生成器NUM_THREADS次之外,循环并没有真正做任何事情所以循环应该如此只需要替换为以下内容。但是我没有检查你的逻辑以及范围是否正确或任何东西。

my_flights->startState = rand() % 1+2;

建议的行动方案

您应该将线程视为一个小程序或应用程序。我建议对于这个简单的例子,你首先编写你的飞行逻辑而不用担心线程。所以如果你从一个函数开始,说你传递一个飞行变量的FlyPlaneFlight (),然后这个函数调用其他函数做各种事情,当飞行结束时,它返回给调用者,你可能会在线程的好地方。在为单个航班准备好逻辑后,您可以使用pthread库通过初始化航班数据创建多个航班,然后创建使用FlyPlaneFlight()的线程。

您还需要考虑时间和互动。对于这种模拟,我怀疑你会希望FlyPlaneFlight()函数有一个循环,其中对飞行数据进行了更改,然后线程将睡眠一两秒。作为开始测试,使用具有确定迭代次数的for循环,然后退出,如下所示:

for (int i = 0; i < 100; i++) {
    // modify the flight data
    sleep(1000);   // sleep for a second (1000 milliseconds) then repeat
}

如果这变得更复杂,以致飞行不是独立的但必须以某种方式同步,则需要查看pthread库的线程同步功能。

因此,当您将FlyPlaneFlight()函数包装到pthread_create()函数中时,它可能类似于以下源代码段:

void *FlightID(void *flightdata){
    struct flight_data *my_flights = (struct flight_data*)flightdata;

    // initialize the flight data as needed
    FlyPlaneFlight (myFlight);
    // print out the myFlight data so that you can see what happened
    pthread_exit(NULL);
}

我们的想法是将飞机飞行视为一个对象,并且该飞行所需的所有数据都在struct flight_data结构中,并且在大多数情况下,您可以忽略不参与该飞行的pthread库。实际的飞行模拟,而是用于模拟多个飞行物体。因此,您创建多个线程,每个线程都有自己的航班数据,然后使用相同的代码处理航班数据。你做了一些随机化,以便所有不同的航班都有不同的历史,他们会做不同的事情。

修改

你的主人将有一个像下面这样的循环

for (t=0; t<NUM_THREADS; t++){                    //loop creates threads(flights)
    std::cout << "In main: Creating flight " << t+1 << std::endl;
    flights[t].fid= t+1;
    rc = pthread_create(&planes[t], NULL, FlightID, (void *)&flights[t]);
    if (rc){
        std::cout << "ERROR: return code from pthread_create() is " << rc << std::endl;
        return (-1);
    }
    std::cout << "Created flight " << t << std::endl;
}
pthread_exit(NULL);    // exit the main thread and allow remaining threads to complete

这将创建各种线程并让它们运行。在FlyPlaneFlight()函数的循环中,每次循环时都会打印出类似下面的状态,这样你的FlyPlaneFlight()函数看起来就像是,你会使用{{3}可能使用随机数生成器使用finite state machine滚动虚拟骰子以确定下一个状态或保持当前状态,从状态移动到状态:

void FlyPlaneFlight (struct flight_data *my_flights)
{
    for (int i = 0; i < 100; i++) {
        switch (my_flights->startState) {
            case 1:
                std::cout << "Flight # " << my_flights->fid << " is listed as waiting at the gate." << std::endl;
                // now move the flight state to the next state.
                break;
            case 2:
                std::cout << "Flight # " << my_flights->fid << " is listed as waiting to land." << std::endl;
                // now move the flight state to the next state.
                break;
            // other case statements for other flight states and moving between the
            // various flight states.
        }
        sleep (1000);  // sleep this thread for one second (1000 milliseconds) then repeat
    }
}

编辑#2基于源更新10/06 at 22:37

在您的源代码中,您有一个全局数组变量flights,您尝试直接通过源代码访问。这是一个导致你陷入困境的错误。您需要做的是让您的线程创建调用以将特定线程的特定数组元素分配给特定线程。然后在那时你不用担心flight数组,而只使用分配给该线程的特定元素。

例如,使用如下的线程create,它创建一个线程并为正在创建的线程分配一个唯一的数组元素。

rc = pthread_create(&planes[t], NULL, FlightID, (void *)&flights[t]);

线程入口函数FlightID()接受指向该数组元素的指针作为参数,因此此时对flights[t]中的飞行数据进行操作的任何函数都可以使用该指针数组元素。这些功能应该只是担心他们的特定飞行,而不是其他所有人的飞行。

在线程启动之后,函数FlightID()及其调用的任何函数都不再需要关注其他线程,因此这些函数中所有这些带NUM_THREADS的循环都不应该存在。

这个想法是通过调用在特定航班上运行的FlightID()来启动一个小程序。然后使用多个线程,每个线程从FlightID()开始。所以这类似于main()作为C / C ++程序入口点的想法,其中main()有一些参数,你的程序从main()开始。在线程的情况下,线程从线程入口函数开始,在你的情况下是FlightID()

我在FlyPlaneFlight()中有一个循环的原因是为特定航班的有限状态机提供一系列状态更改。换句话说,循环内部的是飞机飞行。

看看我建议的线程创建循环与你的之间的区别。我只做创建线程。你创建线程,然后尝试使用flight数组元素,它实际上应该属于创建的线程,而不是主线。

答案 1 :(得分:0)

所有这些变量似乎都存储在flights数组中,而不是planes数组中。