I am trying to start a method from my main() as a new thread with pthread:
int main(int argc, char** argv) {
pthread_t shipGeneratorThread;
Port portMelbourne;
pthread_create(&shipGeneratorThread, NULL, portMelbourne.generateShips(), NULL);
return (EXIT_SUCCESS);
}
The Port class has a function that generates a ship:
void Port::generateShips() {
//Generate 1 cargo ship every 2.5 hours
bool stop = false;
while(!stop) {
if(numberOfShipsInBay < 20) {
Ship ship;
ship.setTicket(numberOfShipsInBay);
shipsWaitingToDock[numberOfShipsInBay] = ship;
term.displayMessage("A new ship has entered the port");
numberOfShipsInBay++;
} else {
term.displayMessage("A ship has been sent to another port");
}
usleep(FIVE_MINUTES * 30); //2.5 hours simulated time
}
}
But the compiler gives me an error, “invalid use of void expression” for the pthread create function.
I am new to C++ and threading, any ideas?
you should use static method in this case and yes, look into man pthread_create.
Signature of functiona is significant.
Also if you create thread way your code show it will be terminated as soon as main() exits.
You need to wait for thread to accomplish. I put example below. It is not ideal but seems good enough for demonstration.
Please pay attention to static -> non-static method transition while handling thread start. It is common approach (although not the only one possible).