pthread_create()详解

本文详细解析了pthread_create()函数,通过实例展示了如何使用该函数创建线程,并介绍了其在多线程编程中的作用。

pthread_create()函数声明

#include <pthread.h> 

int pthread_create(pthread_t * thread ,const pthread_attr_t * attr ,
                          void *(* start_routine )(void *),void * arg ); 

 

thread指向的地址存储创建的线程号;
attr 这个参数是一个 pthread_attr_t 结构体的指针,用来在线程创建的时候指定新线程的属性。如果在创建线程时,这个参数指定为 NULL, 那么就会使用默认属性。
新线程通过调用start_routine()开始执行; arg作为start_routine()的唯一参数传递

下面举个例子

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

using namespace std;

#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
    // 对传入的参数进行强制类型转换,由无类型指针变为整形数指针,然后再读取
    long tid = *((long*)threadid);
    cout << "Hello Runoob! 线程 ID, " << tid << endl;
    pthread_exit(NULL);
}

int main ()
{
    pthread_t threads[NUM_THREADS];//用来存储线程ID
    int indexes[NUM_THREADS];// 用数组来保存i的值
    int rc;
    int i;
    for( i=0; i < NUM_THREADS; i++ ){
        cout << "main() : 创建第"<<i<<"个线程"<< endl;
        //indexes[i] = i; //先保存i的值
        // 传入的时候必须强制转换为void* 类型,即无类型指针
        rc = pthread_create(&threads[i], NULL,
                            PrintHello, (void *)&(threads[i]));
        cout<<threads[i]<<endl;
        if (rc){
            cout << "Error:无法创建线程," << rc << endl;
            exit(-1);
        }
    }
    pthread_exit(NULL);
}

输出:

main() : 创建第0个线程
0x700006700000
main() : 创建第1个线程
Hello Runoob! 线程 ID, 123145410314240
0x700006783000
main() : 创建第2个线程
Hello Runoob! 线程 ID, 123145410850816
0x700006806000
main() : 创建第3个线程
0x700006889000
main() : 创建第4个线程
Hello Runoob! 线程 ID, 123145411923968
0x70000690c000
Hello Runoob! 线程 ID, 123145411387392
Hello Runoob! 线程 ID, 123145412460544

123145410314240的16进制表示就是0x700006700000。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值