我正在創建一個程序來練習使用線程。我試圖給他們起個名字,這樣當程序運行時,您可以清楚地看到「航班1正在起飛......」或「航班6正在着陸......」等等。我希望每個線程都有一個flyTime(所以我知道他們將使用跑道的順序),這將隨機生成。我嘗試過,並且使用struct/typedef給每個pthread賦予這些特性有困難,所以我可以說例如flight.flyTime並在整個程序中使用它。這裏是我的代碼的相關部分沒有我的起飛/降落功能:命名線程,使用typedef /結構
#include <pthread.h>
#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <queue>
#define NUM_THREADS 8 //8 flights
pthread_mutex_t runway1lock;
void *FlightID(void *flightid){
long fid;
fid = (long)flightid;
pthread_exit(NULL);
}
typedef struct{ //each plane has these characteristics
long fid;
int StartState; // if start=1 ==> taking off:::if start=2 ==> landing
int flyTime; //fly == randomly generated time (order)
}FLIGHTS;
FLIGHTS flights[NUM_THREADS];
int StartState(flights[NUM_THREADS]){
int startState;
for (int i=0; i<=NUM_THREADS; i++){
startState = rand() % 1+2;
}
std::string start;
if(startState == 1){
start = "Taking off";
}
if(startState == 2){
start = "Landing";
}
for (int t=0; t<NUM_THREADS; t++){
std::cout << "Start State for Flight# " << FlightID << " is " << start << std::endl;
}
return startState;
}
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 rc;
long t;
for (t=1; t<=NUM_THREADS; t++){ //loop creates threads(flights)
printf("In main: Creating flight %1d\n", t);
rc = pthread_create(&flights[t], NULL, FlightID, (void *)t);
if (rc){
printf("ERROR: return code from pthread_create() is %d\n", rc);
return (-1);
}
printf("Created flight %1d\n", t);
StartState(flights[t]); //gives every flight a start state
if(StartState(flights[t])==1){
std::cout << "Flight # " << &flights[t] << " is listed as waiting at the gate." << std::endl;
//go to takeoff function and go through switch case
}
if(StartState(flights[t])==2){`enter code here`
std::cout << "Flight # " << &flights[t] << " is listed as waiting to land." << std::endl;
//go to landing function and go through switch case
}
}
pthread_exit(NULL);
}
你爲什麼不使用C++線程?你的代碼看起來非常像C和一些C++擴展...... – Walter
說實話,我不熟悉C或C++,所以我不確定如何使用與上述不同的線程。我可以成功地打印出「創建航班1,創建航班1,創建航班2,創建航班2」等等,但是使用%1d - 當我開始使用FlightID時......「1號航班是列爲等待着陸「打印多次,這意味着FlightID並沒有被分配給每個線程(而不是我所希望的 – Anna
),因此目前尚不清楚您實際嘗試實現的目標。也許你可以生成一個SSCCE? – Walter