如何为成员对象的过程启动新线程

发布于 2024-09-17 08:37:23 字数 975 浏览 5 评论 0原文

我试图从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

沉默的熊 2024-09-24 08:37:23

在这种情况下你应该使用静态方法,是的,看看 man pthread_create 。
functiona 的签名很重要。

此外,如果您创建线程方式,您的代码显示它将在 main() 退出后立即终止。
您需要等待线程完成。我在下面举了例子。它并不理想,但似乎足以用于演示。

请注意静电->处理线程启动时的非静态方法转换。这是常见的方法(尽管不是唯一可能的方法)。

#include <stdio.h>
#include <pthread.h>

class Test {
    public:
        static void* Run(void* me) {
            static_cast<Test*>(me)->RunMe();
            return NULL;
        }

    private:
        void RunMe() {
            printf("%p: %p is running.\n", pthread_self(), this);
        }
};

int main() {

    pthread_t tid;
    Test test;

    printf("%p: creating thread for %p is running.\n", pthread_self(), &test);
    pthread_create(&tid, NULL, Test::Run, &test);
    printf("%p: waiting %p to finish.\n", pthread_self(), &test);

    // In real code you should check 'create' operation result.
    pthread_join(tid, NULL);
    printf("%p: OK, exiting\n", pthread_self());

    return 0;
}

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).

#include <stdio.h>
#include <pthread.h>

class Test {
    public:
        static void* Run(void* me) {
            static_cast<Test*>(me)->RunMe();
            return NULL;
        }

    private:
        void RunMe() {
            printf("%p: %p is running.\n", pthread_self(), this);
        }
};

int main() {

    pthread_t tid;
    Test test;

    printf("%p: creating thread for %p is running.\n", pthread_self(), &test);
    pthread_create(&tid, NULL, Test::Run, &test);
    printf("%p: waiting %p to finish.\n", pthread_self(), &test);

    // In real code you should check 'create' operation result.
    pthread_join(tid, NULL);
    printf("%p: OK, exiting\n", pthread_self());

    return 0;
}
咋地 2024-09-24 08:37:23

您需要“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.

鹊巢 2024-09-24 08:37:23
/* you need a wrapper function like this, it can be also a static method of some class */
void *GenerateShipsThread(void *port)
{
    /* do desired action */
    reinterpret_cast<Port*>(port)->generateShips();

    /* destroy Port object here or somewhere else */
    delete reinterpret_cast<Port*>(port);

    return NULL;
}

int main(int argc, char** argv) {
    pthread_t shipGeneratorThread;

    /* Port object is passed to the thread so you don't want it to be
     * destoyed when this function returns - create it on the heap */
    Port *portMelbourne = new Port();

    pthread_create(&shipGeneratorThread, NULL, GenerateShipsWrapper, portMelbourne);

    return (EXIT_SUCCESS);
}
/* you need a wrapper function like this, it can be also a static method of some class */
void *GenerateShipsThread(void *port)
{
    /* do desired action */
    reinterpret_cast<Port*>(port)->generateShips();

    /* destroy Port object here or somewhere else */
    delete reinterpret_cast<Port*>(port);

    return NULL;
}

int main(int argc, char** argv) {
    pthread_t shipGeneratorThread;

    /* Port object is passed to the thread so you don't want it to be
     * destoyed when this function returns - create it on the heap */
    Port *portMelbourne = new Port();

    pthread_create(&shipGeneratorThread, NULL, GenerateShipsWrapper, portMelbourne);

    return (EXIT_SUCCESS);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文