C++之多线程编程-三

来源:互联网 发布:安兔兔数据作假 编辑:程序博客网 时间:2024/06/06 20:58

C++之多线程编程

有时候在调用线程函数的时候需要给线程传进去参数,下面说下,在线程函数中传入参数的方法

代码如下,依然是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 次运行结果不一致

0 0