zoukankan      html  css  js  c++  java
  • 多线程编程:线程调用函数时传入参数

      重点:注意pthread_create() 第四个参数的使用  

      下面给出经典例程(来源:CSDN姜团长):

    #include <iostream>
    #include <pthread.h>
    
    using namespace std;
    
    #define NUM_THREADS 10
    
    void* say_hello(void* args)
    {
        int i = *((int*)args);//对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取;
        cout << "hello in " << i << endl;
    }
    
    int main()
    {
        pthread_t tids[NUM_THREADS];
        cout << "hello in main..." << endl;
        for(int i = 0; i < NUM_THREADS; ++i)
        {
            int ret = pthread_create(&tids[i], NULL, say_hello, (void *)&i);//传入的时候必须强制转换为void* 类型,即无类型指针
            cout << "Current pthread id =" << tids[i] << endl;//这里学会使用tids数组打印创建的进程id信息;
            if (ret != 0)
            {
               cout << "pthread_create error: error_code=" << ret << endl;
            }
        }
    
        pthread_exit(NULL);
    }
    ————全心全意投入,拒绝画地为牢
  • 相关阅读:
    JVM(三)初始化
    JVM(四)类加载机制
    JVM(一)内存分配
    java的日期时间处理(待更新)
    Java----finally
    FFmpeg(一)
    SqlServer
    MySql 8.0.12安装、配置
    Android的各大框架整理
    互联网协议入门
  • 原文地址:https://www.cnblogs.com/Bw98blogs/p/7637007.html
Copyright © 2011-2022 走看看