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。