1.使用CreatThread创建
#include <iostream> #include <Windows.h> using namespace std; /* 创建一个线程 */ DWORD WINAPI fun(LPVOID ipParamter) { while (true) { cout << "fun1 display!" << endl; Sleep(1000); } } /* 创建第二个线程 */ DWORD WINAPI fun2(LPVOID i) { while (true) { cout << "fun2 " << endl; Sleep(1500); } } int main() { //第二个参数0是初始的字节,第五个参数0是便是立即开始线程 HANDLE hThread = CreateThread(NULL, 0, fun, NULL, 0, NULL); HANDLE hThread2 = CreateThread(NULL, 0, fun2, NULL, 0, NULL); CloseHandle(hThread); CloseHandle(hThread2); while (true) { cout << "main display!" << endl; Sleep(2000); } return 0; }
使用CreatThread创建线程是不安全的,容易造成内存泄漏(CRT相关),所以推荐使用_beginThread或_beginThreadex,它内部也使用了CreatThread,但是在使用前做了很多工作以确保其安全性。
2.使用_beginThread创建
#include <iostream> #include <Windows.h> #include <process.h> using namespace std; void fun1() { while (true) { cout << "fun1 display\n"; Sleep(1000); } } unsigned _stdcall fun2(void * ) { while (true) { cout << "fun2 display\n"; Sleep(1000); } } int main() { unsigned int thID1, thID2; HANDLE hfun1, hfun2; hfun1 = (HANDLE)_beginthread((void(*)(void*))fun1, 0, NULL); hfun2 = (HANDLE)_beginthreadex(NULL, 0, fun2, NULL, 0, &thID2); WaitForSingleObject(hfun1, INFINITE); //一定要等子线程完毕 WaitForSingleObject(hfun2, INFINITE); CloseHandle(hfun1); CloseHandle(hfun2); cout << "end\n"; return 0; }
3.std::thread
C++11以来支持了thread类,方便了多线程的创建管理。
#include <mutex> #include <iostream> #include <thread> #include <windows.h> using namespace std; mutex m; void f() { cout << "using..." << endl; } int a; void fun1(int i) { while (true) { m.lock(); //a++; cout << "f1"<< endl; Sleep(1000); f(); Sleep(5000); m.unlock(); } } void fun2() { while (true) { m.lock(); // a--; cout << "f2"<< endl; Sleep(1000); f(); Sleep(1000); m.unlock(); } } int main() { a = 1; thread th(fun1, 1); thread ti(fun2); th.join(); ti.join(); return 0; }
相关博客:C++:线程(std::thread)