线程
线程的创建
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*routine)(void *), void *arg);
成功返回0,失败时返回错误码
thread 线程对象
attr 线程属性,NULL代表默认属性
routine 线程执行的函数
arg 传递给routine的参数 ,参数是void * ,注意传递参数格式,
编译错误分析:
- createP_t.c:14:36: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types]
ret = pthread_create(&tid,NULL,testThread,NULL);
^
In file included from createP_t.c:1:0:
/usr/include/pthread.h:233:12: note: expected ‘void * (*)(void )’ but argument is of type ‘int * ()(char *)’
意义:表示pthread_create参数3的定义和实际代码不符合,期望的是void * (*)(void ) ,实际的代码是int * ()(char *)
解决方法:改为pthread_create(&tid,NULL,(void*)testThread,NULL);
- createP_t.c:(.text+0x4b):对‘pthread_create’未定义的引用
collect2: error: ld returned 1 exit status --------这个链接错误,
表示pthread_create这个函数没有实现
解决方法:编译时候加 -lpthread
注意事项:1. 主进程的退出,它创建的线程也会退出。 线程创建需要时间,如果主进程马上退出,那线程不能得到执行
获取线程的id
通过pthread_create函数的第一个参数;通过在线程里面调用pthread_self函数
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int *testThread(char *arg){
printf("This is a thread text\n");
return NULL;
}
int main()
{
pthread_t tid;
int ret;
ret=pthread_create(&tid,NULL,(void * )testThread,NULL);
printf("This is main thread\n");
sleep(1);
return 0;
}
线程间参数传递:(重点难点)
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *testThread(void *arg){
printf("This is a thread text,pid=%d,tid=%lu\n",getpid(),pthread_self());
printf("arg=%d\n",*(int *)arg);//printf("arg=%d\n",(int)arg);
return NULL;
}
int main() {
pthread_t tid;
int ret;
int arg=5;
ret=pthread_create(&tid,NULL,testThread,(void *)&arg);//ret=pthread_create(&tid,NULL,testThread,(void *)arg);
printf("This is main thread,tid=%lu\n",tid);
sleep(1);
return 0;
}
编译错误:
createP_t.c:8:34: warning: dereferencing ‘void *’ pointer
printf(“input arg=%d\n”,(int)*arg); ^
createP_t.c:8:5: error: invalid use of void expression
printf(“input arg=%d\n”,(int)arg);
错误原因是void 类型指针不能直接用取值(arg),因为编译不知道数据类型。
解决方法:转换为指定的指针类型后再用取值 比如:(int *)arg
- 通过地址传递参数,注意类型的转换
- 值传递,这时候编译器会告警,需要程序员自己保证数据长度正确
运行错误:
*** stack smashing detected ***: ./mthread_t terminated
已放弃 (核心已转储)
原因:栈被破坏了(数组越界)
线程的回收
使用pthread_join 函数:
#include <pthread.h>
int pthread_join(pthread_t thread, void **retval);
对于一个默认属性的线程 A 来说,线程占用的资源并不会因为执行结束而得到释放
成功返回0,失败时返回错误码
thread 要回收的线程对象
调用线程阻塞直到thread结束
*retval 接收线程thread的返回值
注意:pthread_join 是阻塞函数,如果回收的线程没有结束,则一直等待
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *testThread(void *arg){
printf("This is child thread\n");
sleep(5);
pthread_exit("exit exit");
}
int main()
{
pthread_t tid;
void *ret;
ret=pthread_create(&tid,NULL,testThread,NULL);
pthread_join(tid,&ret);
printf("Thread ret=%s\n",(char *)ret);
sleep(1);
}
This is child thread
Thread ret=exit exit
编译错误:
pjoin.c:13:5: error: unknown type name ‘pthead_t’
pthead_t tid;
错误类型:未知的类型pthead_t
错误可能:1拼写错误,2对应的头文件没有包含
pjoin.c:18:12: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘void ’ [-Wformat=]
printf(“thread ret=%s\n”,retv);
错误类型:参数不匹配,期望的是char * ,但参数retv是void *
解决:在参数前面加强制类型转换(char)retv
线程的分离
两种方式:
1 使用pthread_detach
int pthread_detach(pthread_t thread);
成功:0;失败:错误号
指定该状态,线程主动与主控线程断开关系。线程结束后(不会产生僵尸线程)
2 创建线程时候设置为分离属性
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *func(void *arg){
printf("This is child thread\n");
sleep(25);
pthread_exit("thread return");
}
int main(){
pthread_t tid[100];
void *retv;
int i;
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED);
for(i=0;i<100;i++){
pthread_create(&tid[i],&attr,func,NULL);
// pthread_detach(tid);
}
while(1){
sleep(1);
}
}
线程的取消
意义:随时杀掉一个线程
int pthread_cancel(pthread_t thread);
注意:线程的取消要有取消点才可以,不是说取消就取消,线程的取消点主要是阻塞的系统调用
运行段错误调试:
可以使用gdb调试
使用gdb 运行代码,gdb ./youapp
(gdb) run
等待出现Thread 1 “pcancel” received signal SIGSEGV, Segmentation fault.
输入命令bt(打印调用栈)
(gdb) bt
#0 0x00007ffff783ecd0 in vfprintf () from /lib/x86_64-linux-gnu/libc.so.6
#1 0x00007ffff78458a9 in printf () from /lib/x86_64-linux-gnu/libc.so.6
#2 0x00000000004007f9 in main () at pcancel.c:21
确定段错误位置是pcancel.c 21行
如果没有取消点,手动设置一个
void pthread_testcancel(void);
设置取消使能或禁止
int pthread_setcancelstate(int state, int *oldstate);
PTHREAD_CANCEL_ENABLE
PTHREAD_CANCEL_DISABLE
设置取消类型
int pthread_setcanceltype(int type, int *oldtype);
PTHREAD_CANCEL_DEFERRED 等到取消点才取消
PTHREAD_CANCEL_ASYNCHRONOUS 目标线程会立即取消
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *func(void *arg){
printf("This is child thread\n");
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE,NULL);
// while(1)
{
sleep(5);
pthread_testcancel();
}
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE,NULL);
while(1){
sleep(1);
}
pthread_exit("thread return");
}
int main(){
pthread_t tid;
void *retv;
int i;
pthread_create(&tid,NULL,func,NULL);
sleep(1);
pthread_cancel(tid);
pthread_join(tid,&retv);
// printf("thread ret=%s\n",(char*)retv);
while(1){
sleep(1);
}
}
线程的清理
必要性: 当线程非正常终止,需要清理一些资源。
void pthread_cleanup_push(void (*routine) (void *), void *arg)
void pthread_cleanup_pop(int execute)
routine 函数被执行的条件:
- 被pthread_cancel取消掉。
- 执行pthread_exit
- 非0参数执行pthread_cleanup_pop()
注意:
- 必须成对使用,即使pthread_cleanup_pop不会被执行到也必须写上,否则编译错误。
- pthread_cleanup_pop()被执行且参数为0,pthread_cleanup_push回调函数routine不会被执行.
- pthread_cleanup_push 和pthread_cleanup_pop可以写多对,routine执行顺序正好相反
- 线程内的return 可以结束线程,也可以给pthread_join返回值,但不能触发pthread_cleanup_push里面的回调函数,所以我们结束线程尽量使用pthread_exit退出线程。
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void cleanup(void *arg){
printf("cleanup,arg=%s\n",(char*)arg);
}
void cleanup2(void* arg){
printf("cleanup2,arg=%s\n",(char*)arg);
}
void *func(void *arg){
printf("This is child thread\n");
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS,NULL);
pthread_cleanup_push(cleanup,"abcd");
pthread_cleanup_push(cleanup2,"efgh");
//while(1)
{
sleep(1);
}
// pthread_cancel(pthread_self());
//printf("Should not print\n");
return "1234";
while(1){
printf("sleep\n");
sleep(1);
}
pthread_exit("thread return");
pthread_cleanup_pop(1);
pthread_cleanup_pop(1);
sleep(10);
pthread_exit("thread return");
}
int main(){
pthread_t tid;
void *retv;
int i;
pthread_create(&tid,NULL,func,NULL);
sleep(1);
// pthread_cancel(tid);
pthread_join(tid,&retv);
printf("thread ret=%s\n",(char*)retv);
while(1){
sleep(1);
}
}
线程的互斥和同步
临界资源概念:
不能同时访问的资源,比如写文件,只能由一个线程写,同时写会写乱。
比如外设打印机,打印的时候只能由一个程序使用。
外设基本上都是不能共享的资源。
生活中比如卫生间,同一时间只能由一个人使用。
必要性: 临界资源不可以共享
man手册找不到 pthread_mutex_xxxxxxx (提示No manual entry for pthread_mutex_xxx)的解决方法:
apt-get install manpages-posix-dev
互斥锁的创建和销毁
两种方法创建互斥锁,静态方式和动态方式
动态方式:
int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);
其中mutexattr用于指定互斥锁属性,如果为NULL则使用缺省属性。
静态方式:
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
锁的销毁
int pthread_mutex_destroy(pthread_mutex_t *mutex)
在Linux中,互斥锁并不占用任何资源,因此LinuxThreads中的 pthread_mutex_destroy()除了检查锁状态以外(锁定状态则返回EBUSY)没有其他动作。
互斥锁的使用:
int pthread_mutex_lock(pthread_mutex_t *mutex)
int pthread_mutex_unlock(pthread_mutex_t *mutex)
int pthread_mutex_trylock(pthread_mutex_t *mutex)
vim 设置代码全文格式化:gg=G
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
FILE *fp;
void *func2(void *arg){
pthread_detach(pthread_self());
printf("This func2 thread\n");
char str[]="I write func2 line\n";
char c;
int i=0;
while(1){
pthread_mutex_lock(&mutex);
while(i<strlen(str))
{
c = str[i];
fputc(c,fp);
usleep(1);
i++;
}
pthread_mutex_unlock(&mutex);
i=0;
usleep(1);
}
pthread_exit("func2 exit");
}
void *func(void *arg){
pthread_detach(pthread_self());
printf("This is func1 thread\n");
char str[]="You read func1 thread\n";
char c;
int i=0;
while(1){
pthread_mutex_lock(&mutex);
while(i<strlen(str))
{
c = str[i];
fputc(c,fp);
i++;
usleep(1);
}
pthread_mutex_unlock(&mutex);
i=0;
usleep(1);
}
pthread_exit("func1 exit");
}
int main(){
pthread_t tid,tid2;
void *retv;
int i;
fp = fopen("1.txt","a+");
if(fp==NULL){
perror("fopen");
return 0;
}
pthread_create(&tid,NULL,func,NULL);
pthread_create(&tid2,NULL,func2,NULL);
while(1){
sleep(1);
}
}
读写锁
必要性:提高线程执行效率
特性:
写者:写者使用写锁,如果当前没有读者,也没有其他写者,写者立即获得写锁;否则写者将等待,直到没有读者和写者。
读者:读者使用读锁,如果当前没有写者,读者立即获得读锁;否则读者等待,直到没有写者。
注意:
同一时刻只有一个线程可以获得写锁,同一时刻可以有多个线程获得读锁。
读写锁出于写锁状态时,所有试图对读写锁加锁的线程,不管是读者试图加读锁,还是写者试图加写锁,都会被阻塞。
读写锁处于读锁状态时,有写者试图加写锁时,之后的其他线程的读锁请求会被阻塞,以避免写者长时间的不写锁
操作 | 指令 |
---|---|
初始化一个读写锁 | pthread_rwlock_init |
读锁定读写锁 | pthread_rwlock_rdlock |
非阻塞读锁定 | pthread_rwlock_tryrdlock |
写锁定读写锁 | pthread_rwlock_wrlock |
非阻塞写锁定 | pthread_rwlock_trywrlock |
解锁读写锁 | pthread_rwlock_unlock |
释放读写锁 | pthread_rwlock_destroy |
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
pthread_rwlock_t rwlock;
FILE *fp;
void * read_func(void *arg){
pthread_detach(pthread_self());
printf("read thread\n");
char buf[32]={0};
while(1){
//rewind(fp);
pthread_rwlock_rdlock(&rwlock);
while(fgets(buf,32,fp)!=NULL){
printf("%d,rd=%s\n",(int)arg,buf);
usleep(1000);
}
pthread_rwlock_unlock(&rwlock);
sleep(1);
}
}
void *func2(void *arg){
pthread_detach(pthread_self());
printf("This func2 thread\n");
char str[]="I write func2 line\n";
char c;
int i=0;
while(1){
pthread_rwlock_wrlock(&rwlock);
while(i<strlen(str))
{
c = str[i];
fputc(c,fp);
usleep(1);
i++;
}
pthread_rwlock_unlock(&rwlock);
i=0;
usleep(1);
}
pthread_exit("func2 exit");
}
void *func(void *arg){
pthread_detach(pthread_self());
printf("This is func1 thread\n");
char str[]="You read func1 thread\n";
char c;
int i=0;
while(1){
pthread_rwlock_wrlock(&rwlock);
while(i<strlen(str))
{
c = str[i];
fputc(c,fp);
i++;
usleep(1);
}
pthread_rwlock_unlock(&rwlock);
i=0;
usleep(1);
}
pthread_exit("func1 exit");
}
int main(){
pthread_t tid1,tid2,tid3,tid4;
void *retv;
int i;
fp = fopen("1.txt","a+");
if(fp==NULL){
perror("fopen");
return 0;
}
pthread_rwlock_init(&rwlock,NULL);
pthread_create(&tid1,NULL,read_func,1);
pthread_create(&tid2,NULL,read_func,2);
pthread_create(&tid3,NULL,func,NULL);
pthread_create(&tid4,NULL,func2,NULL);
while(1){
sleep(1);
}
}
死锁
概念:
避免方法:
- 锁越少越好,最好使用一把锁
- 调整好锁的顺序
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutex2 = PTHREAD_MUTEX_INITIALIZER;
FILE *fp;
void *func2(void *arg){
pthread_detach(pthread_self());
printf("This func2 thread\n");
char str[]="I write func2 line\n";
char c;
int i=0;
while(1){
pthread_mutex_lock(&mutex);
printf("%d,I got lock2\n",(int)arg);
sleep(1);
pthread_mutex_lock(&mutex2);
printf("%d,I got 2 locks\n",(int)arg);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex1);
sleep(10);
}
pthread_exit("func2 exit");
}
void *func(void *arg){
pthread_detach(pthread_self());
printf("This is func1 thread\n");
char str[]="You read func1 thread\n";
char c;
int i=0;
while(1){
pthread_mutex_lock(&mutex);
printf("%d,I got lock1\n",(int)arg);
sleep(1);
pthread_mutex_lock(&mutex2);
printf("%d,I got 2 locks\n",(int)arg);
pthread_mutex_unlock(&mutex2);
pthread_mutex_unlock(&mutex);
sleep(10);
}
pthread_exit("func1 exit");
}
int main(){
pthread_t tid,tid2;
void *retv;
int i;
fp = fopen("1.txt","a+");
if(fp==NULL){
perror("fopen");
return 0;
}
pthread_create(&tid,NULL,func,1);
pthread_create(&tid2,NULL,func2,2);
while(1){
sleep(1);
}
}
条件变量
应用场景:生产者消费者问题,是线程同步的一种手段。
必要性:为了实现等待某个资源,让线程休眠。提高运行效率
int pthread_cond_wait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex,
const struct timespec *restrict abstime);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
使用步骤:
- 初始化:
静态初始化
pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //初始化条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //初始化互斥量
或使用动态初始化
pthread_cond_init(&cond);
- 生产资源线程:
pthread_mutex_lock(&mutex);
开始产生资源 pthread_cond_sigal(&cond); //通知一个消费线程
或者 pthread_cond_broadcast(&cond); //广播通知多个消费线程
pthread_mutex_unlock(&mutex);
- 消费者线程:
pthread_mutex_lock(&mutex);
while (如果没有资源){ //防止惊群效应
pthread_cond_wait(&cond, &mutex);
} 有资源了,消费资源
pthread_mutex_unlock(&mutex);
注意:
- pthread_cond_wait(&cond, &mutex),在没有资源等待是是先unlock 休眠,等资源到了,再lock所以pthread_cond_wait he pthread_mutex_lock 必须配对使用。
-
如果pthread_cond_signal或者pthread_cond_broadcast 早于 pthread_cond_wait ,则有可能会丢失信号。
-
pthead_cond_broadcast 信号会被多个线程收到,这叫线程的惊群效应。所以需要加上判断条件while循环。
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
pthread_cond_t hasTaxi=PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
struct taxi{
struct taxi *next;
int num;
};
struct taxi *Head=NULL;
void *taxiarv(void *arg){
printf("taxi arrived thread\n");
pthread_detach(pthread_self());
struct taxi *tx;
int i=1;
while(1){
tx = malloc(sizeof(struct taxi));
tx->num = i++;
printf("taxi %d comming\n",tx->num);
pthread_mutex_lock(&lock);
tx->next = Head;
Head = tx;
pthread_cond_signal(&hasTaxi);
//pthread_cond_broadcast(&hasTaxi);
pthread_mutex_unlock(&lock);
sleep(1);
}
pthread_exit(0);
}
void *takeTaxi(void *arg){
printf("take taxi thread\n");
pthread_detach(pthread_self());
struct taxi *tx;
while(1){
pthread_mutex_lock(&lock);
while(Head==NULL)
{
pthread_cond_wait(&hasTaxi,&lock);
}
tx = Head;
Head=tx->next;
printf("%d,Take taxi %d\n",(int)arg,tx->num);
free(tx);
pthread_mutex_unlock(&lock);
}
pthread_exit(0);
}
int main(){
pthread_t tid1,tid2,tid3;
pthread_create(&tid1,NULL,taxiarv,NULL);
// sleep(5);
pthread_create(&tid2,NULL,takeTaxi,(void*)1);
pthread_create(&tid2,NULL,takeTaxi,(void*)2);
pthread_create(&tid2,NULL,takeTaxi,(void*)3);
while(1) {
sleep(1);
}
}
线程池概念和使用
概念:
通俗的讲就是一 个线程的池子,可以循环的完成任务的一组线程集合
必要性:
我们平时创建一个线程,完成某一个任务,等待线程的退出。但当需要创建大量的线程时,假设T1为创建线程时间,T2为在线程任务执行时间,T3为线程销毁时间,当 T1+T3 > T2,这时候就不划算了,使用线程池可以降低频繁创建和销毁线程所带来的开销,任务处理时间比较短的时候这个好处非常显著。
线程池的基本结构:
- 任务队列,存储需要处理的任务,由工作线程来处理这些任务
- 线程池工作线程,它是任务队列任务的消费者,等待新任务的信号
线程池的实现
- 创建线程池的基本结构:
任务队列链表
typedef struct Task;
线程池结构体
typedef struct ThreadPool; - 线程池的初始化:
pool_init()
{
创建一个线程池结构
实现任务队列互斥锁和条件变量的初始化
创建n个工作线程
} - 线程池添加任务
pool_add_task
{
判断是否有空闲的工作线程
给任务队列添加一个节点
给工作线程发送信号newtask
} - 实现工作线程
workThread
{
while(1){
等待newtask任务信号
从任务队列中删除节点
执行任务
}
} - 线程池的销毁
pool_destory
{
删除任务队列链表所有节点,释放空间
删除所有的互斥锁条件变量
删除线程池,释放空间
}
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define POOL_NUM 10
typedef struct Task{
void *(*func)(void *arg);
void *arg;
struct Task *next;
}Task;
typedef struct ThreadPool{
pthread_mutex_t taskLock;
pthread_cond_t newTask;
pthread_t tid[POOL_NUM];
Task *queue_head;
int busywork;
}ThreadPool;
ThreadPool *pool;
void *workThread(void *arg){
while(1){
pthread_mutex_lock(&pool->taskLock);
pthread_cond_wait(&pool->newTask,&pool->taskLock);
Task *ptask = pool->queue_head;
pool->queue_head = pool->queue_head->next;
pthread_mutex_unlock(&pool->taskLock);
ptask->func(ptask->arg);
pool->busywork--;
}
}
void *realwork(void *arg){
printf("Finish work %d\n",(int)arg);
}
void pool_add_task(int arg){
Task *newTask;
pthread_mutex_lock(&pool->taskLock);
while(pool->busywork>=POOL_NUM){
pthread_mutex_unlock(&pool->taskLock);
usleep(10000);
pthread_mutex_lock(&pool->taskLock);
}
pthread_mutex_unlock(&pool->taskLock);
newTask = malloc(sizeof(Task));
newTask->func = realwork;
newTask->arg = arg;
pthread_mutex_lock(&pool->taskLock);
Task *member = pool->queue_head;
if(member==NULL){
pool->queue_head = newTask;
}else{
while(member->next!=NULL){
member=member->next;
}
member->next = newTask;
}
pool->busywork++;
pthread_cond_signal(&pool->newTask);
pthread_mutex_unlock(&pool->taskLock);
}
void pool_init(){
pool = malloc(sizeof(ThreadPool));
pthread_mutex_init(&pool->taskLock,NULL);
pthread_cond_init(&pool->newTask,NULL);
pool->queue_head = NULL;
pool->busywork=0;
for(int i=0;i<POOL_NUM;i++){
pthread_create(&pool->tid[i],NULL,workThread,NULL);
}
}
void pool_destory(){
Task *head;
while(pool->queue_head!=NULL){
head = pool->queue_head;
pool->queue_head = pool->queue_head->next;
free(head);
}
pthread_mutex_destroy(&pool->taskLock);
pthread_cond_destroy(&pool->newTask);
free(pool);
}
int main(){
pool_init();
sleep(20);
for(int i=1;i<=20;i++){
pool_add_task(i);
}
sleep(5);
pool_destory();
}
线程的GDB调试
显示线程
info thread
切换线程
thread id
GDB为特定线程设置断点
break location thread id
GDB设置线程锁,
set scheduler-locking on/off
on:其他线程会暂停。可以单独调试一个线程