计算斐波那契数的线程程序
我正在尝试用 C++ 编写一个程序来计算斐波那契数列。我创建一个执行计算和输出的线程。但我的 for 循环中似乎没有任何内容被执行。任何人都可以看一下我的代码并告诉我我可能做错了什么吗?
#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//iterative with output
DWORD WINAPI fib3(LPVOID param){
double u = 0;
double v = 1;
double t;
int upper = *(int*)param;
for(int i = 2; i <= upper; i++){
cout << v << " ";
t = u + v;
u = v;
v = t;
cout << "testing" << endl;
}
cout << v << " ";
return 0;
}
int main(int argc, char *argv[]){
cout << "This will compute the fibonacci series.\n" << endl;
bool done = true;
double x;
DWORD ThreadId;
HANDLE ThreadHandle;
while(done){
cout << "Enter a number: ";
cin >> x;
if(x == -1){
cout << "\nExiting" << endl;
return 0;
}
ThreadHandle = CreateThread(NULL, 0, fib3, &x, 0, &ThreadId);
if(ThreadHandle != NULL){
WaitForSingleObject(ThreadHandle, INFINITE);
CloseHandle(ThreadHandle);
}
}
return 0;
}
I'm trying to write a program in C++ to compute the Fibonacci series. I create a thread that does the calculation and output. But nothing in my for loop seems to get executed. Can anyone have a look at my code and tell me what I might be doing wrong?
#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
//iterative with output
DWORD WINAPI fib3(LPVOID param){
double u = 0;
double v = 1;
double t;
int upper = *(int*)param;
for(int i = 2; i <= upper; i++){
cout << v << " ";
t = u + v;
u = v;
v = t;
cout << "testing" << endl;
}
cout << v << " ";
return 0;
}
int main(int argc, char *argv[]){
cout << "This will compute the fibonacci series.\n" << endl;
bool done = true;
double x;
DWORD ThreadId;
HANDLE ThreadHandle;
while(done){
cout << "Enter a number: ";
cin >> x;
if(x == -1){
cout << "\nExiting" << endl;
return 0;
}
ThreadHandle = CreateThread(NULL, 0, fib3, &x, 0, &ThreadId);
if(ThreadHandle != NULL){
WaitForSingleObject(ThreadHandle, INFINITE);
CloseHandle(ThreadHandle);
}
}
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您将 double 的地址传递给 CreateThread,然后尝试在线程函数中将其视为 int * 。将
double x;
更改为int x;
You're passing the address of a double to CreateThread, then you try to treat it as an int * in the thread func. Change
double x;
toint x;