一、什么是线程?
线程是进程的一个实体,是CPU调度和分派的基本单位,它是比进程更小的能独立运行的基本单位。线程自己基本上不拥有系统资源,只拥有一点在运行中必不可少的资源(如程序计数器,一组寄存器和栈),但是它可与同属一个进程的其他的线程共享进程所拥有的全部资源。
二、什么时候使用多线程? 当多个任务可以并行执行时,可以为每个任务启动一个线程。
三、线程的创建 使用pthread_create函数。
#include<pthread.h> int pthread_create (pthread_t *__restrict __newthread,//新创建的线程ID __const pthread_attr_t *__restrict __attr,//线程属性 void *(*__start_routine) (void *),//新创建的线程从start_routine开始执行 void *__restrict __arg)//执行函数的参数
返回值:成功-0,失败-返回错误编号,可以用strerror(errno)函数得到错误信息
四、线程的终止 三种方式线程从执行函数返回,返回值是线程的退出码线程被同一进程的其他线程取消调用pthread_exit()函数退出。这里不是调用exit,因为线程调用exit函数,会导致线程所在的进程退出。
一个小例子:
启动两个线程,一个线程对全局变量num执行加1操作,执行五百次,一个线程对全局变量执行减1操作,同样执行五百次。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
int num=0;
void *add(void *arg) {//线程执行函数,执行500次加法
int i = 0,tmp;
for (; i <500; i++)
{
tmp=num+1;
num=tmp;
printf("add+1,result is:%dn",num);
}
return ((void *)0);
}
void *sub(void *arg)//线程执行函数,执行500次减法
{
int i=0,tmp;
for(;i<500;i++)
{
tmp=num-1;
num=tmp;
printf("sub-1,result is:%dn",num);
}
return ((void *)0);
}
int main(int argc, char** argv) {
pthread_t tid1,tid2;
int err;
void *tret;
err=pthread_create(&tid1,NULL,add,NULL);//创建线程
if(err!=0)
{
printf("pthread_create error:%sn",strerror(err));
exit(-1);
}
err=pthread_create(&tid2,NULL,sub,NULL);
if(err!=0)
{
printf("pthread_create error:%sn",strerror(err));
exit(-1);
}
err=pthread_join(tid1,&tret);//阻塞等待线程id为tid1的线程,直到该线程退出
if(err!=0)
{
printf("can not join with thread1:%sn",strerror(err));
exit(-1);
}
printf("thread 1 exit code %dn",(int)tret);
err=pthread_join(tid2,&tret);
if(err!=0)
{
printf("can not join with thread1:%sn",strerror(err));
exit(-1);
}
printf("thread 2 exit code %dn",(int)tret);
return 0;
}
使用g++编译该文件(g++ main.cpp -o main)。此时会报错undefined reference to `pthread_create'。








