C++:创建线程初试
来源:互联网 发布:dnf游戏数据异常严重吗 编辑:程序博客网 时间:2024/05/17 20:12
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)
阅读全文
0 0
- C++:创建线程初试
- C 线程的创建
- C语言初试
- C 语言创建线程池
- windows下c创建线程
- C 语言创建线程池
- C/C++ 创建线程解析
- 【C语言】【unix c】线程的创建
- 用C创建新线程的源码
- C创建新线程的源码
- 线程池原理及创建(c++)
- C语言创建线程-简单例程
- Linux C线程的创建和使用
- Android NDK c创建新的线程
- Linux C线程的创建和使用
- linux用C语言创建线程池
- 调用C底层进行线程创建
- Linux C线程的创建和使用
- URL
- python:一个比较有趣的脚本
- C++:虚函数
- 小练习:补数 (Number Complement)
- 小练习:Two Sum
- C++:创建线程初试
- 小练习:vaild number
- C++:override和final
- 如何编写静态库
- 根据数据库查询返回值,返回时间段
- C++:类和对象
- 函数指针
- main函数的参数:argc和argv
- mac osx Apache 服务器架设