C++ 多线程编程

很多的时候我们在写代码的时候会遇到多线程 接下来我简单谢了一个多线程的程序 直接上代码

#include <iostream>
using namespace std;
#include <pthread.h>
#define NUM_THERADS 5
void * say_hello(void * args)
{
    cout << "Hello Runoob!" <<*((int *)args) << endl;
    return 0;
}
/*
原型:int  pthread_create((pthread_t  *thread,  pthread_attr_t  *attr,  void  *(*start_routine)(void  *),  void  *arg)

用法:#include  <pthread.h>

功能:创建线程(实际上就是确定调用该线程函数的入口点),在线程创建以后,就开始运行相关的线程函数。

说明:thread:线程标识符;

    attr:线程属性设置;
    
    start_routine:线程函数的起始地址;
    
    arg:传递给start_routine的参数;
    
    返回值:成功,返回0;出错,返回-1。
*/
int main()
{
    pthread_t tids[NUM_THERADS];
    static int j =0;
    for(int i= 0;i<NUM_THERADS; ++i)
    {
        j++;
       int ret = pthread_create(&tids[i],NULL,say_hello,(void *)&(j));
       if(ret != 0)
       {
           cout << "pthread_create error : error_code"<< ret <<  endl;
       }
    }
    pthread_exit(NULL);
}

猜你喜欢

转载自www.cnblogs.com/wanghuixi/p/8966025.html