zoukankan      html  css  js  c++  java
  • C++ Multithread Tutorial

    ---恢复内容开始---

    Example 1

    Creating and terminating thread by using

    pthread_create, pthread_exit(status)

    #include <iostream>
    #include <cstdlib>
    #include <pthread.h>
    
    using namespace std;
    
    #define NUM_THREADS     5
    
    void *PrintHello(void *threadid)
    {
       long tid;
       tid = (long)threadid;
       cout << "Hello World! Thread ID, " << tid << endl;
       pthread_exit(NULL);
    }
    
    int main ()
    {
       pthread_t threads[NUM_THREADS];
       int rc;
       int i;
       for( i=0; i < NUM_THREADS; i++ ){
          cout << "main() : creating thread, " << i << endl;
          rc = pthread_create(&threads[i], NULL, 
                              PrintHello, (void *)i);
          if (rc){
             cout << "Error:unable to create thread," << rc << endl;
             exit(-1);
          }
       }
       pthread_exit(NULL);
    }
    

    compile it with g++ xxx.cpp -o test -lphread

    Example 2

    Passing Arguments to Threads

    #include <iostream>
    #include <cstdlib>
    #include <pthread.h>
    
    using namespace std;
    
    #define NUM_THREAD 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 << endl;
    	cout << "message : " << my_data->message << endl;
    
    	pthread_exit(NULL);
    }
    
    int main()  {
    	pthread_t threads[NUM_THREAD];
    	struct thread_data td[NUM_THREAD];
    
    	int rc;
    	int i;
    
    	for(i = 0; i < NUM_THREAD; i ++)  {
    		cout << "main() : creating thread " << i << endl;
    		td[i].thread_id = i;
    		td[i].message = "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);
    }
    

    Example 3

    Joining and Detaching thread

    ---恢复内容结束---

  • 相关阅读:
    Android使用sqlliteOpenhelper更改数据库的存储路径放到SD卡上
    递归实现全排列(一)
    poj_1284_原根
    绝对让你理解Android中的Context
    Java Web---登录验证和字符编码过滤器
    ceph理论及部署配置实践
    ceph for openstack快速部署实施
    php set env
    基于本地iso 搭建的本地yum源 安装部署openldap
    ceph rpm foor rhel6
  • 原文地址:https://www.cnblogs.com/zhouzhuo/p/3710116.html
Copyright © 2011-2022 走看看