C++之多线程编程-三
2015-03-15 14:48
190 查看
C++之多线程编程
有时候在调用线程函数的时候需要给线程传进去参数,下面说下,在线程函数中传入参数的方法
代码如下,依然是C++控制台程序
运行结果如下
再次运行
再次运行
可以看出 3 次运行结果不一致
有时候在调用线程函数的时候需要给线程传进去参数,下面说下,在线程函数中传入参数的方法
代码如下,依然是C++控制台程序
#include "stdafx.h" #include <iostream> #include <pthread.h> //多线程头文件,可移植众多平台, pthread头文件和库需要自己下载, //下载地址 https://sourceware.org/pthreads-win32/#download //进入下载网站找到相应的 .exe下载即可,各种版本均可 #define NUM_THREADS 5 //进程数 using namespace std; class hhh { public: //如何在线程函数中传入参数 static void * sayHello( void * args) { //对传入的参数进行强制类型转换,由无类型指针转变为整形指针,再用*读取其指向到内容 int i = *((int *)args); std:: cout<< "hello "<< i <<endl; return NULL; } }; int _tmain(int argc, _TCHAR* argv[]) { pthread_t tids[NUM_THREADS]; //进程 id int indexex[NUM_THREADS]; //用来保存i的值避免被修改 for (int i = 0; i < NUM_THREADS; i ++) { //参数1创建的线程id,参数2 线程参数,参数3 线程运行函数的地址,参数4函数的参数 //传入的参数必须强制转换为 void * 类型,即无类型指针,取出 i 的地址 &i indexex[i] = i; int ret = pthread_create(&tids[i], NULL, hhh::sayHello, (void *)&(indexex[i])); if (ret != 0)//创建线程成功返回 0 { std::cout<<"pthread_create error:error_code"<<endl; } } for (int i = 0; i < NUM_THREADS; i ++) { //pthread_join 用来等待一个线程的结束,是一个线程阻塞的函数 //不加此方法可能出现运行过程中出错 //代码中如果没有pthread_join主线程会很快结束从而使整个线程结束,从而是创建的线程 //没有开始执行就结束了,加入pthread_join后,主线程会等待,知道等待的线程结束,主线程 //才结束,是创建的线程有机会执行 pthread_join(tids[i], NULL); } //等待各个线程退出后,进程才结束,否则进程强制结束,线程处于未终止的状态 pthread_exit(NULL); return 0; }
运行结果如下
再次运行
再次运行
可以看出 3 次运行结果不一致
相关文章推荐
- C++“多线程安全”编程完全剖析
- Windows 下 C/C++ 多线程编程入门参考范例
- C++多线程编程入门
- c/c++: 多线程编程基础讲解(一)
- Windows 下 C/C++ 多线程编程入门参考范例
- C++多线程编程
- c/c++: 多线程编程基础讲解(五)
- c++多线程编程安全性简单说明
- c++多线程编程安全性简单说明
- c/c++: 多线程编程基础讲解(三)
- [zt] C++多线程编程入门
- c/c++: 多线程编程基础讲解(二)
- c/c++: 多线程编程基础讲解(一)
- Linux下C++的多线程编程---(转载)
- c/c++: 多线程编程基础讲解(六)
- C++ 多线程编程 封装多线程api 类似java多线程风格
- c++ 多线程编程常用的几个函数
- c/c++: 多线程编程基础讲解(四)
- C++ 多线程编程实例
- c/c++: 多线程编程基础讲解(四)