一、多线程基本概念
1> 线程:也称为轻量版的进程(LWP),是更小的任务执行单元,是进程的一个执行路径
2> 线程是任务器调度的最小单位
3> 一个进程中可以包含多个线程,多个线程共享进程的资源。
4> 线程几乎不占用资源,只是占用了很少的用于程序状态的资源(大概有8k左右)
5> 由于多个线程共同使用进程的资源,导致,线程在操作上容易出现不安全的状态
6> 线程操作开销较小、任务切换效率较高
7> 一个进程中,至少要包含一个线程(主线程)
8> 在有任务执行漫长的IO等待过程中,可以同时执行其他任务
9> linux中不直接支持线程相关的支持库,需要引入第三方库,线程支持库
sudo apt-get install manpages-posix manpages-posix-dev
如果程序中使用的线程支持库中的函数,编译程序时,需要加上 -lpthread 选项
二、线程支持函数(多线程编程)
2.1 pthread_create:创建线程
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
功能:在当前进程中,创建一个分支线程
参数1:用于接收创建好的线程ID
参数2:线程的属性,一般填NULL表示使用系统默认的属性创建线程
参数3:线程体函数,需要传递一个函数,参数为void*,返回值为void*
参数4:参数3的参数
返回值:成功创建返回0,失败返回一个错误码,注意,不是内核提供的错误码
#include<myhead.h>
//定义一个用于传递数据的结构体类型
struct Buf
{
int num;
double key;
};
//定义线程体函数
void *task(void *arg)
{
int num = (*((struct Buf*)arg)).num;
double key = ((struct Buf*)arg)->key;
while(1)
{
printf("我是分支线程, num = %d, key=%.2lf\n", num, key);
sleep(1);
}
}
/************************主程序*****************************/
int main(int argc, const char *argv[])
{
int num = 520; //定义整形变量
double key = 1314; //定义浮点型数据
struct Buf buf = {num, key}; //封装要传递的数据
//定义变量存储线程号
pthread_t tid = -1;
//创建分支线程
if(pthread_create(&tid, NULL, task, &buf) != 0)
{
printf("pthread_create error\n");
return -1;
}
printf("我是主线程,tid = %#lx\n", tid);
//while(1);
getchar();
return 0;
}
2.2 pthread_self:线程号的获取
#include <pthread.h>
pthread_t pthread_self(void);
功能:获取当前线程的线程号
参数:无
返回值:当前线程的线程号
2.3 pthread_exit:线程退出函数
#include <pthread.h>
void pthread_exit(void *retval);
功能:退出当前的线程
参数:线程退出时的状态,一般填NULL
返回值:无
2.4 pthread_jion : 线程资源的回收
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
功能:阻塞等待给定线程的退出,并回收该线程的资源
参数1:要回收的线程号
参数2:接收线程退出时的状态
返回值:成功返回0,失败返回错误码
2.5 pthread_detach:线程分离态
#include <pthread.h>
int pthread_detach(pthread_t thread);
功能:将线程设置成分离态,设置了分离态的线程,退出后,由系统回收其资源
参数:要被分离的线程id号
返回值:成功返回0,失败返回错误码
2.6 pthread_setcancelstate:设置取消属性
#include <pthread.h>
int pthread_setcancelstate(int state, int *oldstate);
功能:设置是否接收取消指令
参数1:新的状态
PTHREAD_CANCEL_ENABLE:可接受状态
PTHREAD_CANCEL_DISABLE:不可接收状态
参数2:线程的旧的状态容器,如果不愿意要之前的状态,填NULL即可
返回值:成功返回0,失败返回错误码
#include<myhead.h>
//定义线程体函数
void *task(void *arg)
{
//设置线程不可取消状态
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
printf("我是分支线程,线程号为:%#lx\n", pthread_self());
//exit(EXIT_SUCCESS); //退出进程
int count = 0;
while(1)
{
printf("我真的还想再活五百年。。。。\n");
sleep(1);
count++;
if(count == 10)
{
break;
}
}
pthread_exit(NULL); //退出线程
}
/************************主程序*****************************/
int main(int argc, const char *argv[])
{
//定义变量存储线程号
pthread_t tid = -1;
//创建分支线程
if(pthread_create(&tid, NULL, task, NULL) != 0)
{
printf("pthread_create error\n");
return -1;
}
printf("我是主线程,tid = %#lx, 主线程线程号:%#lx\n", tid, pthread_self());
/*回收分支线程的资源
if(pthread_join(tid, NULL) == 0)
{
printf("成功回收了%#lx的资源\n", tid);
}*/
//将线程设置成分离态
pthread_detach(tid);
printf("线程已经分离\n");
//休眠5秒
sleep(5);
//向分之线程中发送一个取消请求
pthread_cancel(tid);
//while(1);
getchar();
return 0;
}
2.7 多线程允许使用同一个线程体函数
#include<myhead.h>
void *task(void *arg)
{
//判断传过来的信息 (char *)arg
if(strcmp( (char*)arg, "hello") == 0)
{
//线程1执行的内容
int num = 10;
while(num--)
{
printf("我真的还想再活五百年\n");
sleep(1);
}
//退出线程
pthread_exit(NULL);
}else if( strcmp( (char*)arg, "world") == 0 )
{
//线程2执行的内容
sleep(5);
printf("啦啦啦啦啦啦,我是卖报的小行家\n");
pthread_exit(NULL);
}
}
/*******************主程序*********************/
int main(int argc, const char *argv[])
{
//定义线程变量
pthread_t tid1, tid2;
//创建两个线程
if(pthread_create(&tid1, NULL, task, "hello") != 0)
{
printf("tid1 创建失败\n");
return -1;
}
if(pthread_create(&tid2, NULL, task, "world") != 0)
{
printf("tid2 创建失败\n");
return -1;
}
//阻塞等等线程的结束
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
return 0;
}
使用两个线程完成两个文件的拷贝,分支线程1拷贝前一半,分支线程2拷贝后一半,主线程回收两个分支线程的资源
#include <myhead.h>
//定义线程接受的结构体
typedef struct sa
{
const char *a; //源文件
const char *b; //目标文件
int (*c)(const char *srcfile, const char *destfile, int start, int len); //接受拷贝函数
int len; //接受源文件字节大小
int flag; //用于区分线程的标志
} buf, *buf_ptr;
//求源文件字节大小
int get_file_len(const char *srcfile, const char *destfile)
{
//以只读的形式打开源文件
int sfd = open(srcfile, O_RDONLY);
if (sfd == -1)
{
perror("open srcfile error");
return -1;
}
//以创建的形式打开目标文件
int dfd = open(destfile, O_WRONLY | O_CREAT | O_TRUNC, 0664);
if (dfd == -1)
{
perror("open destfile error");
return -1;
}
int size = lseek(sfd, 0, SEEK_END);
//关闭文件
close(sfd);
close(dfd);
return size; //将文件大小返回
}
int copy_file(const char *srcfile, const char *destfile, int start, int len)
{
//以只读的形式打开源文件
int sfd = open(srcfile, O_RDONLY);
if (sfd == -1)
{
perror("open srcfile error");
return -1;
}
//以创建的形式打开目标文件
int dfd = open(destfile, O_WRONLY);
if (dfd == -1)
{
perror("open destfile error");
return -1;
}
//移动光标位置
lseek(sfd, start, SEEK_SET);
lseek(dfd, start, SEEK_SET);
//定义搬运工
char buf[128] = "";
int sum = 0; //记录拷贝的总个数
while (1)
{
//从源文件中读取数据
int res = read(sfd, buf, sizeof(buf));
sum += res; //将读取的个数累加
if (res == 0 || sum > len) //表示文件读取结束
{
write(dfd, buf, res - (sum - len)); //父进程将最后一次拷贝结束
break;
}
//写入到目标文件中
write(dfd, buf, res);
}
//关闭文件
close(sfd);
close(dfd);
printf("拷贝成功\n");
}
void *task(void *arg)
{
const char *p = ((buf_ptr)arg)->a;//接受目标文件
const char *w = ((buf_ptr)arg)->b;//接受源文件
int (*q)(const char *, const char *, int, int) = ((buf_ptr)arg)->c;//接受拷贝函数指针
int len = ((buf_ptr)arg)->len;//接受源文件字节大小
int flag = ((buf_ptr)arg)->flag;//接受标志
if (flag == 0)//标志为0
{
q(p, w, 0, len / 2);//调用拷贝函数拷贝前一半
pthread_exit(NULL);//退出当前线程
}
else if (flag == 1)//标志为1
{
q(p, w, len / 2, len - len / 2);//调用拷贝函数拷贝后一半
pthread_exit(NULL);
}
else
{
printf("error\n");
}
}
int main(int argc, const char *argv[])
{
if (argc != 3)//判断输入是否有三个
{
perror("input error\n");//输入错误
return -1;
}
int len = get_file_len(argv[1], argv[2]);//获取argv【2】文件字节大小
int (*ptr)(const char *, const char *, int, int) = copy_file;//定义函数指针,将拷贝函数放进去
buf bufs = {argv[1], argv[2], ptr, len, 0};//线程1的结构体,标志为0
buf rights = {argv[1], argv[2], ptr, len, 1};//线程2的结构体,标志为1
pthread_t tid = -1;
if (pthread_create(&tid, NULL, task, &bufs) == -1)//创建线程1
{
printf("error\n");
return -1;
}
pthread_t pid = -1;
if (pthread_create(&pid, NULL, task, &rights) == -1)//创建线程2
{
printf("error\n");
return -1;
}
//回收线程
pthread_join(tid, NULL);
pthread_join(pid, NULL);
return 0;
}