c++ - 计算斐波那契数的线程程序

标签 c++ multithreading fibonacci

我正在尝试用 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; 
}

最佳答案

您将 double 型的地址传递给 CreateThread,然后尝试在线程函数中将其视为 int *。将 double x; 更改为 int x;

关于c++ - 计算斐波那契数的线程程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5141485/

相关文章:

c++ - 在 QtCreator 中链接/使用外部库

multithreading - perl 线程自分离

ios - 如何快速检测 IteratorProtocol 的第一次运行?

OCaml 创建斐波那契数列

c++ - 重写 += 运算符 C++

c++ - 这种替代的 'for' 循环语法有什么依据吗?

java.lang.IllegalThreadStateException : Thread already started error when using selectors with SocketChannel

java - 多线程合并排序,添加额外的线程

python - 多重递归函数

c++ - 在哪里可以找到 size_t 的定义?