[英]C++ very simple thread?
在C ++中创建线程的最简单方法是什么? 我想做一个使用已经声明的方法来运行的程序。 就像是:
void task1(){
cout << "Thread started";
}
thread t1 = thread(task1());
我想我想做一个不需要下载任何库的线程,并且我的编译器很可能能够编译。 我想回答的一个大问题是,c ++ 11是什么? 是一种完全不同的语言,还是一堆库?
C ++ 11具有线程库。 一个非常简单的示例是:
#include <iostream>
#include <thread>
void task1()
{
std::cout<<"Thread started\n";
}
int main()
{
std::thread t1(task1);
t.join();
}
如果您不能使用C ++ 11,则取决于您要编写的内容。 下面的“尽可能简单”的线程示例是使用CreateThread函数以非托管Win32代码编写的:
#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;
}
如果使用这种方法,请记住传递给CreateThread的函数指针必须具有签名:
DWORD ThreadFuncion(LPVOID lpParameter);
您可以在MSDN上找到该签名的描述。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.