Linux系统下的多线程遵循POSIX线程接口,称为pthread。编写Linux下的多线程程序,需要使用头文件pthread.h,连接时需要使用库libpthread.a。顺便说一下,Linux下pthread的实现是通过系统调用clone()来实现的。clone()是Linux所特有的系统调用,它的使用方式类似fork,关于clone()的详细情况,有兴趣的读者可以去查看有关文档说明。下面我们展示一个最简单的多线程程序threads.cpp。
#include<iostream>
#include <unistd.h>
#include <pthread.h>
using namespace std;
void *thread(void *ptr)
{
for(int i=0;i<3;i++)
{
sleep(1);
cout<<"Thread p."<<i<<endl;
}
return 0;
}
int main()
{
pthread_t id;
int ret = pthread_create(&id,NULL,thread,NULL);
if(ret){
cout<<"create pthread error!"<<endl;
return 1;
}
for(int i=0;i<3;i++)
{
cout<<"main process."<<i<<endl;
sleep(1);
}
pthread_join(id,NULL);
return 0;
}