c++ 多线程
例子一
#include <iostream> #include <windows.h> using namespace std; DWORD WINAPI Fun(LPVOID lpParamter) { for (int i = 0; i < 10; i++) cout << "A !" << endl; return 0L; } int main() { HANDLE hThread = CreateThread(NULL, 0, Fun, NULL, 0, NULL); CloseHandle(hThread); for (int i = 0; i < 10; i++) cout << "Main!" << endl; return 0; }
输出:
Main!
A !Main!
Main!A !
Main!A !
Main!A !
Main!A !
A !Main!
A !
Main!A !
A !Main!
A !Main!
例子二:
#include <stdlib.h> #include <iostream> #include <list> #include <conio.h> #include <time.h> #include <algorithm> #include <windows.h> //头文件引用较多, 有一些与本程序无关 /* HANDLE WINAPI CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes, //线程安全相关的属性,常置为NULL SIZE_T dwStackSize, //新线程的初始化栈在大小,可设置为0 LPTHREAD_START_ROUTINE lpStartAddress, //被线程执行的回调函数,也称为线程函数 LPVOID lpParameter, //传入线程函数的参数,不需传递参数时为NULL DWORD dwCreationFlags, //控制线程创建的标志 LPDWORD lpThreadId //传出参数,用于获得线程ID,如果为NULL则不返回线程ID ); */ using namespace std; volatile int b = 0; DWORD WINAPI ThreadProc(LPVOID lpParameter) { int i = 10000; int *p = (int*)lpParameter; while(i--) { (*p)++; b++; } return 0; } int main(int argc, char* argv[]) { int a = 0; HANDLE hThread1 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL); HANDLE hThread2 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL); HANDLE hThread3 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL); HANDLE hThread4 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL); HANDLE hThread5 = CreateThread(NULL, 0, ThreadProc, &a, 0, NULL); Sleep(1000); CloseHandle(hThread1); CloseHandle(hThread2); CloseHandle(hThread3); CloseHandle(hThread4); CloseHandle(hThread5); cout << "a = " << a << endl; cout << "b = " << b << endl; system("pause"); return 0; }
输出:
a = 42900 b = 44220