创建线程C++
Creating Pthreads C++
我正在设计俄罗斯方块的重制版,需要一个与输入函数同时运行的计时器函数。我正在使用 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);
}
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- 为什么我不能在 while 循环中创建线程?