zoukankan      html  css  js  c++  java
  • c++ 多线程编程

    http://blog.csdn.net/hitwengqi/article/details/8015646
    1. 基本用法
      #include <iostream>
      #include <pthread.h>
      
      using namespace std;
      
      #define NUM_THREADS 5
      
      void* say_hello(void* args)
      {
          sleep(10);
          cout << "hello..." << endl;
      } //函数返回的是函数指针,便于后面作为参数
      
      int main()
      {
          pthread_t tids[NUM_THREADS];//线程id
          for(int i=0; i < NUM_THREADS; ++i)
          {
              int ret = pthread_create(&tids[i], NULL, say_hello, NULL);//参数:创建线程的id, 线程参数,线程运行函数的起始地址,运行函数的参数
      
              if( ret != 0 ) //创建线程成功返回0http://i.cnblogs.com/EditPosts.aspx?postid=4454529
              {
                  cout << "pthread_create error:error_code" << ret << endl;
              }
          }
          pthread_exit( NULL); //等待各个线程退出后,进程才结束,否则进程强制结束,线程处于未终止的状态
      }
      /* vim: set ts=4 sw=4 sts=4 tw=100 */
      g++ -o muti_thread_test_1 muti_thread_test_1.cpp -lpthread
    2. 线程调用到函数中的一个类中,那必须将该函数声明为静态函数。
      因为静态成员函数属于静态全局区,线程可以共享这个区域,故可以各自调用。
      #include <iostream>
      #include <pthread.h>
      using namespace std;
      
      #define NUM_THREADS 5
      
      class Hello
      {
      public:
          static void* sayHello(void* args)
          {
              cout << "hello ... ..." << endl;
          }
      };
      
      int main()
      {
          pthread_t tids[NUM_THREADS];
          for(int i=0; i < NUM_THREADS; ++i)
          {
              int ret = pthread_create(&tids[i], NULL, Hello::sayHello(), NULL);
              if (ret!=0){
                  cout <<  "pthread_create error:error_code" << ret << endl;
              }
          }
          return 0;
      }
  • 相关阅读:
    日本语教育文法ナ イ形容词
    日本语教育文法和国语教育文法
    Multisim note
    莫比乌斯反演
    【NOIP2015】斗地主(dfs)
    【SCOI2007】降雨量(线段树+讨论)
    CF559C Gerald and Giant Chess(计数DP)
    【NOIP2012】开车旅行(倍增+STL)
    Apache Flink目录遍历(CVE-2020-17519)
    CTF文件包含
  • 原文地址:https://www.cnblogs.com/i80386/p/4454529.html
Copyright © 2011-2022 走看看