如何使用CreateThread()将向量传递给线程?

时间:2015-02-19 19:28:47

标签: windows multithreading vector

我试图创建一个程序,询问用户输入数字并生成斐波那契数字。 Main获取数字并将该数字设置为向量的第一个值。然后将向量发送到线程以生成等于该数字的Fibonacci(因此,如果我键入3,则线程将生成前3个Fibonacci数并将其添加到向量中)。然后向量将返回到main函数,以便它可以打印出值。

这是我所拥有的,但它一直在说Error: expression must be a pointer to a complete object type,我试图打印出矢量的第一个值。

#include <iostream>
#include <windows.h>
#include <vector>
using namespace std;

/* This function is executed by the child thread */
DWORD WINAPI calcFibNumbers(LPVOID fibNumber)
{
    cout << fibNumber[0];

    return 0;
}

/* This is the main function and start of program */
int main()
{
    //Local Variables
    vector<int> fibNumbers;
    int numOfFib;

    //Create child thread
    HANDLE childThread = CreateThread(NULL, 0, calcFibNumbers, &fibNumbers, CREATE_SUSPENDED, NULL);

    //Ask user for the number of fibonacci numbers
    cout << "Enter how many fibonacci numbers you would like the program to generate: ";
    cin >> numOfFib;
    fibNumbers.push_back(numOfFib);

    ResumeThread(childThread);
    if (childThread)
    {
        WaitForSingleObject(childThread, INFINITE);
    }

    getchar();
    getchar();
    return 0;
}

有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:0)

vector<int>* fibNum = (vector<int>*)fibNumber; // pointer

vector<int>& fibNum = *(vector<int>*)fibNumber; // reference