如何为成员对象的过程启动新线程
我试图从 main() 中启动一个方法作为带有 pthread 的新线程:
int main(int argc, char** argv) {
pthread_t shipGeneratorThread;
Port portMelbourne;
pthread_create(&shipGeneratorThread, NULL, portMelbourne.generateShips(), NULL);
return (EXIT_SUCCESS);
}
Port 类有一个生成船舶的函数:
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
}
}
但是编译器给我一个错误,“pthread 创建函数无效使用 void 表达式” 。
我是 C++ 和线程的新手,有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在这种情况下你应该使用静态方法,是的,看看 man pthread_create 。
functiona 的签名很重要。
此外,如果您创建线程方式,您的代码显示它将在 main() 退出后立即终止。
您需要等待线程完成。我在下面举了例子。它并不理想,但似乎足以用于演示。
请注意静电->处理线程启动时的非静态方法转换。这是常见的方法(尽管不是唯一可能的方法)。
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).
您需要“static void*generateShips(void*)”并使用“pthread_create(&shipGeneratorThread, NULL, Port::generateShips, NULL);”启动
“。
问候。
You need "static void* generateShips(void*)" and launch with "pthread_create(&shipGeneratorThread, NULL, Port::generateShips, NULL);
".
Regards.