线程的取消和互斥

取消一个线程

  • int pthread_cancel(pthread_t thread);     杀死一个线程
  • 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    

注意:线程的取消要有取消点才可以,不是说取消就取消,线程的取消点主要是阻塞的系统调用

如果没有取消点,手动设置一个

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 函数被执行的条件:

  1. 被pthread_cancel取消掉。
  2. 执行pthread_exit
  3. 非0参数执行pthread_cleanup_pop()

注意:

  1. 必须成对使用,即使pthread_cleanup_pop不会被执行到也必须写上,否则编译错误。
  2. pthread_cleanup_pop()被执行且参数为0,pthread_cleanup_push回调函数routine不会被执行.
  3. pthread_cleanup_push 和pthread_cleanup_pop可以写多对,routine执行顺序正好相反
  4. 线程内的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());//结束线程,并可以执行cleanup
//    printf("Should not print\n");//如果是默认的取消模式,只有到了取消点才会真正的取消,所以    依然会打印出来,如果是立即取消,则不会打印出来
    return "1234";//结束线程,并不可以执行cleanup

    while(1){
        printf("sleep\n");
        sleep(1);
    }
    pthread_exit("thread return");//结束线程,并可以执行cleanup
    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);
    } 

}

线程的互斥和同步

临界资源  

一次只允许一个任务(进程、线程)访问的共享资源

临界区

访问临界资源的代码

互斥机制

mutex互斥锁

任务访问临界资源前申请锁,访问完后释放锁

临界资源概念:

  • 不能同时访问的资源,比如写文件,只能由一个线程写,同时写会写乱。
  • 比如外设打印机,打印的时候只能由一个程序使用。
  • 外设基本上都是不能共享的资源。
  • 生活中比如卫生间,同一时间只能由一个人使用。

必要性: 临界资源不可以共享

互斥锁的创建和销毁

两种方法创建互斥锁,静态方式动态方式

动态方式

互斥锁初始化 – pthread_mutex_init

#include  <pthread.h>  

int  pthread_mutex_init(pthread_mutex_t *mutex,        const pthread_mutexattr_t *  attr);

  •  成功时返回0,失败时返回错误码  
  • mutex  指向要初始化的互斥锁对象  
  • attr  互斥锁属性,NULL表示缺省属性
  • man 函数出现 No manual entry for pthread_mutex_xxx解决办法  apt-get install manpages-posix-dev

静态方式

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

互斥锁销毁 pthread_mutex_destroy

int pthread_mutex_destroy(pthread_mutex_t *mutex)

在Linux中,互斥锁并不占用任何资源,因此LinuxThreads中的 pthread_mutex_destroy()除了检查锁状态以外(锁定状态则返回EBUSY)没有其他动作。

申请锁 – pthread_mutex_lock

 #include  <pthread.h>  

int  pthread_mutex_lock(pthread_mutex_t *mutex);

int pthread_mutex_trylock(pthread_mutex_t *mutex)

  • 成功时返回0,失败时返回错误码  
  • mutex  指向要初始化的互斥锁对象  
  • pthread_mutex_lock 如果无法获得锁,任务阻塞
  • pthread_mutex_trylock 如果无法获得锁,返回EBUSY而不是挂起等待

释放锁 – pthread_mutex_unlock

 #include  <pthread.h>  

pthread_mutex_unlock(pthread_mutex_t *mutex);

  •  成功时返回0,失败时返回错误码  
  • mutex  指向要初始化的互斥锁对象  
  • 执行完临界区要及时释放锁

互斥锁的实现代码示例

#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);
    } 

}

死锁

避免方法:

  1. 锁越少越好,最好使用一把锁
  2. 调整好锁的顺序

死锁情况的代码示例

#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(&mutex2);
        printf("%d,I got lock2\n",(int)arg);
        sleep(1);
        pthread_mutex_lock(&mutex);
        printf("%d,I got 2 locks\n",(int)arg);

        pthread_mutex_unlock(&mutex);
        pthread_mutex_unlock(&mutex2);
        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);
    } 

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C语言中,线程相关的常用函数包括: 1. pthread_create ```c int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg); ``` 该函数用于创建一个新的线程,参数说明如下: - thread:指向线程标识符的指针,创建成功后会将线程的标识符返回给调用者。 - attr:指定线程的属性,通常使用默认属性即可,传入NULL。 - start_routine:指向线程函数的指针,线程创建后会从该函数开始执行。 - arg:传递给线程函数的参数。 2. pthread_join ```c int pthread_join(pthread_t thread, void **retval); ``` 该函数用于等待一个线程结束,参数说明如下: - thread:等待的线程标识符。 - retval:指向线程返回值存储位置的指针,可以为NULL,表示不关心线程返回值。 3. pthread_detach ```c int pthread_detach(pthread_t thread); ``` 该函数用于将线程设置为分离状态,使得线程结束时能够自动释放资源,参数说明如下: - thread:需要分离的线程标识符。 4. pthread_exit ```c void pthread_exit(void *retval); ``` 该函数用于线程退出,参数说明如下: - retval:线程的返回值。 5. pthread_cancel ```c int pthread_cancel(pthread_t thread); ``` 该函数用于取消一个线程,参数说明如下: - thread:需要取消线程标识符。 6. pthread_mutex_init ```c int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr); ``` 该函数用于初始化一个互斥锁,参数说明如下: - mutex:指向互斥锁的指针。 - attr:指定互斥锁的属性,通常使用默认属性即可,传入NULL。 7. pthread_mutex_destroy ```c int pthread_mutex_destroy(pthread_mutex_t *mutex); ``` 该函数用于销毁一个互斥锁,参数说明如下: - mutex:指向互斥锁的指针。 8. pthread_mutex_lock ```c int pthread_mutex_lock(pthread_mutex_t *mutex); ``` 该函数用于加锁一个互斥锁,参数说明如下: - mutex:指向互斥锁的指针。 9. pthread_mutex_unlock ```c int pthread_mutex_unlock(pthread_mutex_t *mutex); ``` 该函数用于解锁一个互斥锁,参数说明如下: - mutex:指向互斥锁的指针。 10. pthread_cond_init ```c int pthread_cond_init(pthread_cond_t *cond, const pthread_condattr_t *attr); ``` 该函数用于初始化一个条件变量,参数说明如下: - cond:指向条件变量的指针。 - attr:指定条件变量的属性,通常使用默认属性即可,传入NULL。 11. pthread_cond_destroy ```c int pthread_cond_destroy(pthread_cond_t *cond); ``` 该函数用于销毁一个条件变量,参数说明如下: - cond:指向条件变量的指针。 12. pthread_cond_wait ```c int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex); ``` 该函数用于等待一个条件变量,参数说明如下: - cond:指向条件变量的指针。 - mutex:指向互斥锁的指针。 13. pthread_cond_signal ```c int pthread_cond_signal(pthread_cond_t *cond); ``` 该函数用于唤醒一个等待条件变量的线程,参数说明如下: - cond:指向条件变量的指针。 14. pthread_cond_broadcast ```c int pthread_cond_broadcast(pthread_cond_t *cond); ``` 该函数用于广播一个条件变量,唤醒所有等待条件变量的线程,参数说明如下: - cond:指向条件变量的指针。 这些函数在不同的操作系统和编译器中可能有所不同,需要根据具体的使用情况来选择和调用。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值