0

在 C++ 中创建线程的最简单方法是什么?我想做一个使用已经声明的方法来运行的方法。就像是:

 void task1(){
    cout << "Thread started";
 }

 thread t1 = thread(task1());

我想我想创建一个不需要下载任何库并且我的编译器很可能能够编译的线程。我想回答的一个大问题是,什么是 c++11?它是一种完全不同的语言,还是一堆库?

4

3 回答 3

7

C++11 有线程库。一个非常简单的例子是:

#include <iostream>
#include <thread>
void task1()
{
    std::cout<<"Thread started\n";
}
int main()
{
    std::thread t1(task1);
    t.join();
}

请参阅http://en.cppreference.com/w/cpp/thread/thread

于 2013-03-13T02:42:48.397 回答
2

If you can't use C++11, it depends upon what you are programming for. The following "simple as possible" threading example is written in unmanaged Win32 code, using the CreateThread function:

#include <Windows.h>
#include <tchar.h>
#include <iostream>

using namespace std;

DWORD WINAPI ThreadFunction(LPVOID lpParam) {
    WORD numSeconds = 0;
    for (;;) {
        Sleep(1000);
        cout << numSeconds++ << " seconds elapsed in child thread!" << endl;
    }
    return 0;
}

int _tmain(int argc, _TCHAR* argv[]) {
    HANDLE hThread;
    DWORD threadID;
    WORD numSeconds = 0;

    cout << "Hello world" << endl;

    hThread = CreateThread(NULL, 0, ThreadFunction, NULL, 0, &threadID);

    Sleep(500);
    for (;;) {
        cout << numSeconds++ << " seconds elapsed in main thread!" << endl;
        Sleep(1000);
    }

    return 0;
}

If you use this approach, remember that the function pointer passed to CreateThread must have the signature:

DWORD ThreadFuncion(LPVOID lpParameter);

You can find the description of that signature on MSDN.

于 2013-03-13T02:52:25.487 回答
0

C++ 标准每隔几年就会经常修订。添加了一些很酷的东西,并保留了旧的东西以实现向后兼容性。这里有一些历史

Boost在推动 C++ 标准方面有很好的影响。

于 2013-03-13T07:16:55.020 回答