C++并发编程入门 目录
STL 写法
#include <thread>
#include <iostream>
using namespace std;
void thread_fun1(void)
{
cout << "one STL thread 1!" << endl;
}
void thread_fun2(void)
{
cout << "one STL thread 2!" << endl;
}
int main(void)
{
std::thread thread1(thread_fun1);
std::thread thread2(thread_fun2);
thread1.join();
thread2.join();
return 0;
}
Windows 写法
#include <iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI ThreadFun1(LPVOID lpParamter)
{
cout << "one Windows thread 1!" << endl;
return 0;
}
DWORD WINAPI ThreadFun2(LPVOID lpParamter)
{
cout << "one Windows thread 2!" << endl;
return 0;
}
int main()
{
HANDLE hThread1 = CreateThread(NULL, 0, ThreadFun1, NULL, 0, NULL);
HANDLE hThread2 = CreateThread(NULL, 0, ThreadFun2, NULL, 0, NULL);
HANDLE handleArr[] = { hThread1 , hThread2 };
//等待两个线程结束
WaitForMultipleObjects(2, handleArr, TRUE, INFINITE);
CloseHandle(hThread1);
CloseHandle(hThread2);
return 0;
}
三次执行结果



Linux 写法
#include <pthread.h>
#include <iostream>
using namespace std;
void* thread_fun1(void *arg)
{
cout << "one Linux thread 1!" << endl;
return 0;
}
void* thread_fun2(void *arg)
{
cout << "one Linux thread 2!" << endl;
return 0;
}
int main(void)
{
pthread_t thread_id1;
pthread_t thread_id2;
pthread_create(&thread_id1, NULL, thread_fun1, NULL);
pthread_create(&thread_id2, NULL, thread_fun2, NULL);
//让线程运行直到结束
pthread_join(thread_id1, NULL);
pthread_join(thread_id2, NULL);
return 0;
}

