gpt4 book ai didi

c++ - 创建 Pthread C++

转载 作者:行者123 更新时间:2023-11-27 23:22:19 25 4
gpt4 key购买 nike

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

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

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

我注意到另一个人问了几乎相同的问题 here .但是,我设法在另一台计算机上成功创建了 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*

关于c++ - 创建 Pthread C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11962550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com