C++并发编程入门 目录
STL 写法
#include <thread>
#include <iostream>
using namespace std;
void thread_fun(int arg)
{
cout << "one STL thread " << arg << " !" << endl;
}
int main(void)
{
int thread_count = 10;
int id_array[10] = { 1,2,3,4,5,6,7,8,9,10 };
std::thread thread_arr[10] = { };
for (int i = 0; i < thread_count; i++)
{
thread_arr[i] = std::thread(thread_fun, id_array[i]);
}
for (int i = 0; i < thread_count; i++)
{
thread_arr[i].join();
}
return 0;
}
Windows 写法
#include <iostream>
#include <windows.h>
using namespace std;
DWORD WINAPI ThreadFun(LPVOID lpParamter)
{
//转成整数地址,再对地址解引用取出整数
cout << "one Windows thread "<< *(int*)lpParamter<<" !" << endl;
return 0;
}
int main()
{
int thread_count = 10;
HANDLE handleArr[10] = {NULL};
//给线程函数传递的数据,用来标记线程
int data[10] = { 1,2,3,4,5,6,7,8,9,10 };
for (int i = 0; i < 10; i++)
{
handleArr[i] = CreateThread(NULL, 0, ThreadFun, &data[i], 0, NULL);
}
//等待10个线程结束
WaitForMultipleObjects(thread_count, handleArr, TRUE, INFINITE);
for (int i = 0; i < thread_count; i++)
{
CloseHandle(handleArr[i]);
}
return 0;
}
Linux 写法
#include <pthread.h>
#include <iostream>
using namespace std;
void* thread_fun(void *arg)
{
cout << "one Linux thread "<< *(int*)arg<<" !" << endl;
return 0;
}
int main(void)
{
int thread_count = 10;
int id_array[10] = { 1,2,3,4,5,6,7,8,9,10 };
pthread_t thread_arr[10] = { 0 };
for (int i = 0; i < thread_count; ++i)
{
pthread_create(&thread_arr[i], NULL, thread_fun, &id_array[i]);
}
//让线程运行直到结束
for (int i = 0; i < thread_count; i++)
{
pthread_join(thread_arr[i], NULL);
}
return 0;
}