-1

我想使用如下示例代码启动多个线程:

void ThreadFunction(void* param) {
    cout << (string)param << endl;
    _endthread();
    }
int main(int argc, char* argv[]) {
    for (unsigned int i = 1; i <= 10; i++) {
        string String = "This is test nr ";
        String += i;
        _beginthread(ThreadFunction, 0, (void*)&String);
        }
    }

但是,我无法让它工作(分配错误)。我究竟做错了什么?

4

1 回答 1

1

你不能像你正在做的那样传递一个字符串,但你可以传递一个字符串指针。 但!您必须注意字符串至少在线程启动之前保持有效......这通常通过在堆上创建字符串来完成,使用new,但它也可以使用全局对象工作。这是您的代码的工作方式。

#include <unistd.h>
#include <string>
#include <vector>
#include <sstream>
#include <pthread.h>

void ThreadFunction(void* param) 
{
    std::string* s = reinterpret_cast<std::string*>(param);  
    cout << *s << endl;  
}                        // <-- no need to call endthread when exiting gracefully

std::vector<std::string> myStrings;

int main(int argc, char* argv[]) 
{
    // since we will use pointers to strings in the vector myStrings,
    // we need to be sure it is final before using them.
    // you could store some form of smart pointer in the vector to avoid 
    // this issue
    for (unsigned int i = 0; i < 10; i++) 
    {
       std::stringstream ss;
       ss << "This is test nr " << i;
       myStrings.emplace_back(ss.str());
    }

    for (unsigned int i = 0; i < myStrings.size(); i++) 
    {
        _beginthread(FunctionName, 0, &myStrings[i]);
    }

    // we must pause this thread and wait a little while for the threads
    // to run.  _beginthread does not block, and exiting the program too
    // quickly would prevent our background threads from executing...

    sleep(1);

    return 0;
}
于 2017-08-11T09:10:52.210 回答