Linux多线程编程(pthread_creat、pthread_exit、pthread_join、pthread_detach)


前言

线程是一个进程的运行单元,一个进程至少含有一个线程。
  使用多线程的理由之一是和进程相比,它是一种非常"节俭"的多任务操作方式。在Linux系统下,启动一个新的进程必须分配给它独立的地址空间,建立众多的数据表来维护它的代码段、堆栈段和数据段,这是一种"昂贵"的多任务工作方式。而运行于一个进程中的多个线程,它们彼此之间使用相同的地址空间,共享大部分数据,启动一个线程所花费的空间远远小于启动一个进程所花费的空间,而且,线程间彼此切换所需的时间也远远小于进程间切换所需要的时间。据统计,总的说来,一个进程的开销大约是一个线程开销的30倍左右,当然,在具体的系统上,这个数据可能会有较大的区别。
  
  除了以上所说的优点外,不和进程比较,多线程程序作为一种多任务、并发的工作方式,当然有以下的优点:
  1) 提高应用程序响应。这对图形界面的程序尤其有意义,当一个操作耗时很长时,整个系统都会等待这个操作,此时程序不会响应键盘、鼠标、菜单的操作,而使用多线程技术,将耗时长的操作(time consuming)置于一个新的线程,可以避免这种尴尬的情况。
  2) 使多CPU系统更加有效。操作系统会保证当线程数不大于CPU数目时,不同的线程运行于不同的CPU上。
  3) 改善程序结构。一个既长又复杂的进程可以考虑分为多个线程,成为几个独立或半独立的运行部分,这样的程序会利于理解和修改。

注意:

  • 线程依赖与进程存在,如果创建线程的进程结束了,线程也就结束了。
  • 线程函数的程序在pthread库中,故链接时要加上-lpthread。

一、线程创建( pthread_creat() )

原型:
#include <pthread.h>

int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(start_routine)(void), void *arg);

功能:
        创建一个线程

参数:
        thread:线程标识符地址;
        attr:线程属性结构体地址,NULL为默认属性;
        start_routine:线程函数入口地址;
        arg:传给线程的参数

返回值:
        成功:返回0
        失败:返回非0

案例:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
//一个线程的执行顺序是不确定的
//多线程执行是来回切换的
int num = 100;

void *fun1(void *arg)
{
    printf("f1: arg = %d\n", *((int *)arg));
    printf("f1: num = %d\n", num);
    num ++;
}

void *fun2(void *arg)
{
    sleep(1);
    printf("f2: num = %d\n", num);
}

int main()
{
    pthread_t t1,t2;
    int arg = 100; 

    if(pthread_create(&t1, NULL, fun1, (void *)&arg) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    if(pthread_create(&t1, NULL, fun2, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }
    while(1);    //很low的写法
    return 0;
}

运行结果:
在这里插入图片描述
可以看出程序公用一块内存。

执行结果的第一行,先打印pthread_create(&t1, NULL, fun1, (void *)&arg)传过去子线程的arg参数100。
第二行打印num的100。
第三行打印经过线程fun1的语句num++后的num值101。

二、线程退出( pthread_exit() )

原型:
#include <pthread.h>

void pthread_exit(void *value_ptr);

功能:
        退出调用线程。

参数:
        value_ptr:储存线程退出状态的指针。常用static修饰数据类型。

三、线程等待( pthread_join() )

原型:
#include <thread.h>

int pthread_join(thread_t thread, void **status);

功能:
        等待子线程结束,并回收子线程资源。

参数:
        thread:被等待的线程号;
        status:用于存储线程退出状态的指针的地址。

返回值:
        成功:返回0。
        失败:返回非0。

案例:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

//一个线程的执行顺序是不确定的
//多线程执行是来回切换的
void *fun1(void *arg)
{
    static int i = 10;
    printf("子线程1正在执行\n");
    sleep(1);
    printf("**********************\n");
    pthread_exit(&i);
}

void *fun2(void *arg)
{
    static int j = 11;
    printf("子线程2正在执行\n");
    sleep(1);
    printf("---------------------\n");
    pthread_exit(&j);
}

int main()
{
    pthread_t t1,t2;
    int *ptr1 = NULL;
    int *ptr2 = NULL;

    if(pthread_create(&t1, NULL, fun1, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    if(pthread_create(&t2, NULL, fun2, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    pthread_join(t1, (void **)&ptr1);
    pthread_join(t2, (void **)&ptr2);

    printf("f1: exit = %d\n", *ptr1);
    printf("f2: exit = %d\n", *ptr2);
    return 0;
}

执行结果:
在这里插入图片描述
一个线程的执行顺序是不确定的
多线程执行是来回切换的
pthread_join(t1, (void **)&ptr1);第二个参数回收子线程的退出状态,存在ptr1指向的内存。

四、线程分离( pthread_detach() )

原型:
#include <pthread.h>

int pthread_detach(pthread_t thread);

功能:
        使调用线程与当前进程分离,使其成为一个独立的线程,该线程终止时,系统将自动回收它的资源。

参数:
        thread:线程号。

返回值
        成功:返回0。
        失败:返回非0。

案例1://不用线程分离

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

//一个线程的执行顺序是不确定的
//多线程执行是来回切换的
void *fun1(void *arg)
{
    printf("子线程1正在执行\n");
    sleep(1);
    printf("**********************\n");
}

void *fun2(void *arg)
{
    printf("子线程2正在执行\n");
    sleep(1);
    printf("---------------------\n");
}

int main()
{
    pthread_t t1,t2;
    if(pthread_create(&t1, NULL, fun1, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    if(pthread_create(&t2, NULL, fun2, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    if(pthread_join(t2, NULL) != 0){
        perror("fail to pthread_join");
        exit(1);
    }
    if(pthread_join(t1, NULL) != 0){
        perror("fail to pthread_join");
        exit(1);
    }

    while(1){
        printf("hello world\n");
        sleep(1);
    }
    return 0;
}

执行结果:
在这里插入图片描述

案例2://使用线程分离。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

//一个线程的执行顺序是不确定的
//多线程执行是来回切换的
void *fun1(void *arg)
{
    printf("子线程1正在执行\n");
    sleep(1);
    printf("**********************\n");
}

void *fun2(void *arg)
{
    printf("子线程2正在执行\n");
    sleep(1);
    printf("---------------------\n");
}

int main()
{
    pthread_t t1,t2;
    if(pthread_create(&t1, NULL, fun1, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    if(pthread_create(&t2, NULL, fun2, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    pthread_detach(t1);
    pthread_detach(t2);

    #if 0
    if(pthread_join(t2, NULL) != 0){
        perror("fail to pthread_join");
        exit(1);
    }
    if(pthread_join(t1, NULL) != 0){
        perror("fail to pthread_join");
        exit(1);
    }
    #endif

    while(1){
        printf("hello world\n");
        sleep(1);
    }
    return 0;
}

执行结果:
在这里插入图片描述
子线程fun1、fun2与主线程分离。

五、互斥

头文件: #include <pthread.h>

1、互斥锁初始化:pthread_mutex_init()

动态分配互斥锁:int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);

静态分配互斥锁:pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

2、销毁互斥锁:pthread_mutex_destroy()

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

3、上锁和解锁

int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);

案例1: //使用互斥锁

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

int money = 10000;
pthread_mutex_t mutex;

void *fun1(void *arg)
{
    pthread_mutex_lock(&mutex);
    int get, yu, shiji;
    printf("张三正在查询余额......\n");
    sleep(1);
    yu = money;

    printf("张三正在取钱......\n");
    sleep(1);
    get = 1000;

    if(get > yu){
        shiji = 0;
    }
    else{
        shiji = get;
        yu = yu - get;
        money = yu;
    }
    printf("张三想取 %d 块,实际取了 %d 块,余额 %d 块\n", get, shiji, yu);
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

void *fun2(void *arg)
{
    pthread_mutex_lock(&mutex);
    int get, yu, shiji;
    printf("李四正在查询余额......\n");
    sleep(1);
    yu = money;

    printf("李四正在取钱......\n");
    sleep(1);
    get = 1000;

    if(get > yu){
        shiji = 0;
    }
    else{
        shiji = get;
        yu = yu - get;
        money = yu;
    }
    printf("李四想取 %d 块,实际取了 %d 块,余额 %d 块\n", get, shiji, yu);
    pthread_mutex_unlock(&mutex);

    pthread_exit(NULL);
}

int main()
{
    pthread_t t1,t2;
    pthread_mutex_init(&mutex, NULL);

    if(pthread_create(&t1, NULL, fun1, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    if(pthread_create(&t2, NULL, fun2, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    pthread_mutex_destroy(&mutex);
    return 0;
}

执行结果:
在这里插入图片描述

对比案例: //不使用互斥锁

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

int money = 10000;

void *fun1(void *arg)
{
    int get, yu, shiji;
    printf("张三正在查询余额......\n");
    sleep(1);
    yu = money;

    printf("张三正在取钱......\n");
    sleep(1);
    get = 10000;

    if(get > yu){
        shiji = 0;
    }
    else{
        shiji = get;
        yu = yu - get;
        money = yu;
    }
    printf("张三想取 %d 块,实际取了 %d 块,余额 %d 块\n", get, shiji, yu);

    pthread_exit(NULL);
}

void *fun2(void *arg)
{
    int get, yu, shiji;
    printf("李四正在查询余额......\n");
    sleep(1);
    yu = money;

    printf("李四正在取钱......\n");
    sleep(1);
    get = 10000;

    if(get > yu){
        shiji = 0;
    }
    else{
        shiji = get;
        yu = yu - get;
        money = yu;
    }
    printf("李四想取 %d 块,实际取了 %d 块,余额 %d 块\n", get, shiji, yu);

    pthread_exit(NULL);
}

int main()
{
    pthread_t t1,t2;

    if(pthread_create(&t1, NULL, fun1, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    if(pthread_create(&t2, NULL, fun2, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    return 0;
}

执行结果:
在这里插入图片描述
子线程1和子线程2同步执行,结果是不合理的。

六、信号量实现同步

  • 信号量广泛用于进城或线程间的同步和互斥,信号量本质是一个非零的整数计数器,它被用来控制对公共资源的访问。
  • 编程时可根据操作信号量的值判断是否对公共资源具有访问的权限,当信号量值大于零时,则可以访问,否则被阻塞。
  • 一次P操作使信号量sem减1,一次V操作使信号量sem加1。

头文件: #include <semaphore.h>

1、信号量的初始化:sem_init()

int sem_init(sem_t *sem, int pshared, unsigned int value);

2、信号量的销毁:sem_destroy()

int sem_destroy(sem_t *sem);

3、P操作:sem_wait()

int sem_wait(sem_t *sem);
将信号量sem的值减1,若此时信号量的值sem≤0,会引起调用者阻塞。

4、V操作:sem_post()

int sem_post(sem_t *sem);
将信号量sem的值加1,并唤醒等待线程。

5、获取信号量的计数值:sem_getvalue()

int sem_getvalue(sem_t *sem, int *sval);

案例:

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>

//一个线程的执行顺序是不确定的
//多线程执行是来回切换的
sem_t sem_g, sem_p;

char str = '0';

void *fun_get(void *arg)
{   
    while(1){
        sem_wait(&sem_g);
        str++;
        sleep(1);
        sem_post(&sem_p);
    }
}

void *fun_put(void *arg)
{
    while(1){
        sem_wait(&sem_p);
        printf("%c",str);
        fflush(stdout);
        sem_post(&sem_g);
    }
}

int main()
{
    pthread_t t1,t2;
    if(sem_init(&sem_p, 0, 1) != 0){ //fun_put()先执行
        perror("fail to creat sem_init");
        exit(1);
    }

    if(sem_init(&sem_g, 0, 0) != 0){
        perror("fail to creat sem_init");
        exit(1);
    }

    if(pthread_create(&t1, NULL, fun_get, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    if(pthread_create(&t2, NULL, fun_put, NULL) != 0){
        perror("fail to thread creat");
        exit(1);
    }

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);

    printf("\n");
    sem_destroy(&sem_g);
    sem_destroy(&sem_p);
    
    return 0;
}

执行结果:
在这里插入图片描述


本文为作者的学习笔记。 如有错误,敬请原谅,并感谢你的指出。
  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值