创建线程的函数
#include<pthread.h>
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
若成功返回0,否则返回错误编号
创建单个线程:
#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
using namespace std;
void* mythread(void *arg)
{
cout<<"子线程"<<pthread_self()<<" 进程id:"<<getpid()<<endl;
}
int main()
{
pthread_t pid;
int err=pthread_create(&pid,NULL,&mythread,NULL); //调用函数
if(err != 0)
{
cout<<"create error"<<endl;
}
sleep(5);
cout<<"该程序的进程id: "<<getpid()<<endl;
}
循环创建多线程:
创建多线程时不像多进程一样,子线程在下一次循环的时候不会重新创建子子线程,因此不用返回,而直接创建
#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
using namespace std;
void* mythread(void *arg) //传入i值
{
sleep((long)arg);
cout<<(long)arg<<"子线程"<<pthread_self()<<" 进程id:"<<getpid()<<endl;
}
int main()
{
pthread_t pid[5];
int i;
for(i=0;i<5;i++) //循环创建多线程
{
int err=pthread_create(&pid[i],NULL,&mythread,(void *)(intptr_t)i);
if(err != 0)
{
cout<<"create error"<<endl;
}
}
if(i==5)
{
sleep(i); //等待子线程全部运行完
cout<<"该程序的进程id: "<<getpid()<<endl;
}
}