线程的创建
目录
- 线程函数
线程函数
每一个线程都有一个唯一的ID,ID类型为pthread_t,这个ID是一个无符号长整型 unsigned long,如果想要得到当前线程的ID可以调用
pthread_t pthread_self(void);
线程创建:
#include<pthread.h>
int pthread_create(pthread_t *thread,const pthread_attr_t *attr,void* (*start_routine)(void*),void *arg);
- thread:传出参数,线程创建成功,会将线程ID写到这个指针指向的内存中
- attr:线程属性,一般情况使用默认即可,写NULL
- start_routine:函数指针,指向线程要做的任务
- arg:实参
如果成功创建线程,pthread_create() 函数返回数字 0,反之返回非零值
#include<pthread.h>
#include<iostream>
using namespace std;
void * callback(void * arg)
{
for(int i=0;i<5;i++)
{
cout<<"子线程:i="<<i<<endl;
}
cout<<"子线程: "<<pthread_self()<<endl;
return;
}
int main()
{
pthread_t tid;
pthread_create(&tid,NULL,callback,NULL);
for(int i=0;i<5;i++)
{
cout<<"主线程:i= "<<i<<endl;
}
cout<<"主线程: "<<pthread_self()<<endl;
return 0;
}
编译运行结果如下:
主线程:i= 0
主线程:i= 1
主线程:i= 2
主线程:i= 3
主线程:i= 4
主线程: 140333497825088
原因分析:创建完后,主线程拿到时间片,而子线程需要抢cpu的时间片,而子线程还没运行完主线程已经结束退出
在return 0;之前加入sleep函数,让主线程主动放弃时间片,子线程可以运行
sleep(3);