创建线程C++

Creating Pthreads C++

本文关键字:C++ 线程 创建      更新时间:2023-10-16

我正在设计俄罗斯方块的重制版,需要一个与输入函数同时运行的计时器函数。我正在使用 pthreads 来实现这一点,但是当我调用

pthread_create(&timer, NULL, Timer(), NULL);

我收到一个错误,声称尽管在我的标头中包含<pthread.h>,但没有匹配的函数来调用pthread_create()

我注意到另一个人在这里问了几乎相同的问题。但是,我设法在另一台计算机上成功创建了 pthreads,而无需执行任何向该人建议的操作。

以下是我遇到问题的源代码。我不是要求你重写它,而是告诉我出了什么问题。我会做研究来修复我的代码。

#include <pthread.h>
#include <iostream>
#include <time.h>
void *Timer(void) { //I have tried moving the asterisk to pretty much every
                    //possible position and with multiple asterisks. Nothing works
    time_t time1, time2;
    time1 = time(NULL);
    while (time2 - time1 <= 1) {
        time2 = time(NULL);
    }
    pthread_exit(NULL);
}
int main() {
    pthread_t inputTimer;
    pthread_create(&inputTimer, NULL, Timer(), NULL); //Error here
    return 0;
}

谢谢

你需要

传递Timer函数的地址,而不是它的返回值。因此

pthread_create(&inputTimer, NULL, &Timer, NULL); // These two are equivalent
pthread_create(&inputTimer, NULL, Timer, NULL);

pthread_create期望它的第三个参数具有以下类型:void *(*)(void*) ; 即一个接受单个参数的函数 void* 并返回 void*

您需要传递pthread_create您希望它调用的函数的地址,而不是您希望它调用的函数的返回值:

pthread_create(&inputTimer, NULL, Timer, NULL);

此外,您的函数必须具有以下签名void* (void*),因此必须将其更改为:

void *Timer(void*) {
    time_t time1, time2;
    time1 = time(NULL);
    while (time2 - time1 <= 1) {
        time2 = time(NULL);
    }
    pthread_exit(NULL);
}