Linux线程总结

本文总结了Linux线程的相关知识,包括线程的创建、等待、退出,以及线程间共享数据的方法。重点探讨了互斥锁的作用,如何避免死锁,以及条件变量的智能使用。通过实例展示了如何在多线程环境中实现生产者与消费者的条件变量模型。
摘要由CSDN通过智能技术生成

简述

进程与线程的区别:

相同点:多任务处理

不同点:
(1)进程有独立的内存空间(代码段、数据段、堆、栈),线程没有,进程是线程的容器
(2)相对于进程而言,线程间切换效率高,消耗内存小,多线程在同一进程下共享数据(变量),有更为简便的通信机制

常用的线程相关API函数原型(3、4、5)

#include <pthread.h>

// 创建线程、等待、退出
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
int pthread_join(pthread_t thread, void **rval_ptr);
int pthread_exit(void *rval_ptr);

// 互斥锁相关API: 创建锁、上锁、解锁、毁锁
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_lock(pthread_mutex_t *restrict mutex);
int pthread_mutex_unlock(pthread_mutex_t *restrict mutex);
int pthread_mutex_destroy(pthread_mutex_t *restrict mutex);

//条件变量相关API: 创建、触发、广播、等待、销毁  
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_signal(pthread_cond_t *restrict cond);
int pthread_cond_broadcast(pthread_cond_t *restrict cond);
int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
int pthread_cond_destroy(pthread_cond_t *restrict cond);

统一:成功返回0,失败返回-1

线程创建、等待、退出API使用

创建线程、等待线程

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

void *pthread1(void* arg)
{
   
		//打印线程id
        printf("pthread1 creat,id:%ld\n", (unsigned long)pthread_self());
        //线程传参,打印data值,需强转
        printf("data=%d\n", *(int *)arg);

}

// int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// int pthread_join(pthread_t thread, void **rval_ptr);
// int pthread_exit(void *rval_ptr);

int main()
{
   
        int data = 10;

        pthread_t t1;

        printf("before create\n");
        pthread_create(&t1, NULL, &pthread1, (void *)&data);
        printf("after create\n");
		
		pthread_join(t1, NULL);		
//		while(1);
        return 0;
}

线程退出、传参

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

void *pthread1(void* arg)
{
   
//      static int ret = 55;
        static char *ret = "sunshine";

        printf("pthread1 creat,id:%ld\n", (unsigned long)pthread_self());
        printf("data=%d\n", *(int *)arg);

        pthread_exit((void *)ret);
}

// int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// int pthread_join(pthread_t thread, void **rval_ptr);
// int pthread_exit(void *rval_ptr);

int main()
{
   
        int data = 10;
//      int *p = NULL;
        char *pret = NULL;

        pthread_t t1;

        printf("before create\n");
        pthread_create(&t1, NULL
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值