首页 > 技术文章 > C++ 多线程编程

wanghuixi 2018-04-28 09:52 原文

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

#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);//终止现线程
}

 向线程回调函数中传入 结构体

#include <iostream>
#include <cstdlib>
#include <pthread.h>

using namespace std;

#define NUM_THREADS     5

struct thread_data{
   int  thread_id;
   char *message;
};

void *PrintHello(void *threadarg)
{
   struct thread_data *my_data;

   my_data = (struct thread_data *) threadarg;

   cout << "Thread ID : " << my_data->thread_id ;
   cout << " Message : " << my_data->message << endl;

   pthread_exit(NULL);
}

int main ()
{
   pthread_t threads[NUM_THREADS];
   struct thread_data td[NUM_THREADS];
   int rc;
   int i;

   for( i=0; i < NUM_THREADS; i++ ){
      cout <<"main() : creating thread, " << i << endl;
      td[i].thread_id = i;
      td[i].message = (char*)"This is message";
      rc = pthread_create(&threads[i], NULL,
                          PrintHello, (void *)&td[i]);
      if (rc){
         cout << "Error:unable to create thread," << rc << endl;
         exit(-1);
      }
   }
   pthread_exit(NULL);
}

 

推荐阅读