Linux 线程API学习

线程开发的最基本概念主要包含三点:线程,互斥锁,条件

其中,线程操作又分线程的创建,退出,等待 3 种。

互斥锁则包括 4 种操作,分别是创建,销毁,加锁和解锁。

条件操作有 5 种操作:创建,销毁,触发,广播和等待。

其他的一些线程扩展概念,如信号灯等,都可以通过上面的三个基本元素的基本操作封装出来。详细请见下表:
​​​​​​​​​​​​​​​​​​​​​​​​在这里插入图片描述

代码实现

一、线程

1、创建线程

#include <pthread.h>
int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *), void *restrict arg);
// 返回:若成功返回0,否则返回错误编号

当pthread_create成功返回时,由tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于定制各种不同的线程属性,暂可以把它设置为NULL,以创建默认属性的线程。新创建的线程从start_rtn函数的地址开始运行,该函数只有一个无类型指针参数arg。如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg参数传入。

2. 线程退出

单个线程可以通过以下三种方式退出,在不终止整个进程的情况下停止它的控制流:

1)线程只是从启动例程中返回,返回值是线程的退出码。

2)线程可以被同一进程中的其他线程取消。

3)线程调用pthread_exit:

#include <pthread.h>
int pthread_exit(void *rval_ptr);

rval_ptr是一个无类型指针,与传给启动例程的单个参数类似。进程中的其他线程可以通过调用pthread_join函数访问到这个指针。

3. 线程等待

#include <pthread.h>
int pthread_join(pthread_t thread, void **rval_ptr);
// 返回:若成功返回0,否则返回错误编号

调用这个函数的线程将一直阻塞,直到指定的线程调用pthread_exit、从启动例程中返回或者被取消。如果例程只是从它的启动例程返回i,rval_ptr将包含返回码。如果线程被取消,由rval_ptr指定的内存单元就置为PTHREAD_CANCELED。
  
  可以通过调用pthread_join自动把线程置于分离状态,这样资源就可以恢复。如果线程已经处于分离状态,pthread_join调用就会失败,返回EINVAL。
  
  如果对线程的返回值不感兴趣,可以把rval_ptr置为NULL。在这种情况下,调用pthread_join函数将等待指定的线程终止,但并不获得线程的终止状态。

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

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

void *func1(void *arg)
{
  static char *p="t1 run out";//一定是static 类型
  printf("t1:%ld thread is create\n",(unsigned long)pthread_self()); //pthread_self()线程ID获取
  printf("param is %d\n",*((int *)arg));
  pthread_exit ((void *)p);   // 退出
}

 int main()
{
  
  int ret;
  int param=100;
  pthread_t t1;
  
  char *pret;
  ret= pthread_create(&t1, NULL, func1,  (void *)&param);
  if(ret == 0)
    {
       printf("creat t1 success!\n");
    }
  printf("main=%ld\n",(unsigned long)pthread_self());
  pthread_join(t1,(void **)&pret);  //等待
  printf("main:t1 quit :%s\n",pret);

  return 0;
}

二、互斥锁

互斥变量用pthread_mutex_t数据类型表示。在使用互斥变量前必须对它进行初始化,可以把它置为常量PTHREAD_MUTEX_INITIALIZER(只对静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化。如果动态地分配互斥量(例如通过调用malloc函数),那么在释放内存前需要调用pthread_mutex_destroy

  1. 创建及销毁互斥锁
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号

2、 加锁及解锁

#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t mutex); //加锁
int pthread_mutex_trylock(pthread_mutex_t mutex);//解锁
int pthread_mutex_unlock(pthread_mutex_t mutex);
// 返回:若成功返回0,否则返回错误编号

代码示例互斥锁限制共享资源的访问

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

//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *),
// void *restrict arg);
int g_data=0;

pthread_mutex_t mutex;

void *func1(void *arg)
{

  printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
  printf("param is %d\n",*((int *)arg));

  pthread_mutex_lock(&mutex);

  while(1)
    { 
        printf("t1 :%d\n",g_data++);
        sleep(1);
        
        if(g_data == 3 )
          {
             pthread_mutex_unlock(&mutex);
             printf("t1 quit =====================================================\n");
             pthread_exit(NULL);
          }
  
    }


}

void *func2(void *arg)
{

  printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
  printf("param is %d\n",*((int *)arg));
  while(1)
    { 
        printf("t2 :%d\n",g_data);
        pthread_mutex_lock(&mutex);
        g_data++;
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}
 int main()
{
  
  int ret;
  int param=100;
  pthread_t t1;
  pthread_t t2;
  pthread_mutex_init(&mutex,NULL);
  ret= pthread_create(&t1, NULL, func1,  (void *)&param);
  if(ret == 0)
    {
       printf("creat t1 success!\n");
    }

  ret= pthread_create(&t2, NULL, func2,  (void *)&param);
  if(ret == 0)
    {
       printf("creat t2 success!\n");
    }
  while(1)
    { 
        printf("main :%d\n",g_data);
        sleep(1);
    }
  printf("main=%ld\n",(unsigned long)pthread_self());
  pthread_join(t1,NULL);
  pthread_join(t2,NULL);

  pthread_mutex_destroy(&mutex);   //消锁

  return 0;
}

//死锁的原因!
前提条件是要有两把锁,当线程A获取一把锁后想要获取第二把锁。而线程B手里握着线程A想要的锁,同时想要获取A手里的锁。都想获取对方手里的锁都不肯解锁,导致线程死锁的现象。

三、条件

条件变量使用之前必须首先初始化,pthread_cond_t数据类型代表的条件变量可以用两种方式进行初始化,可以把常量PTHREAD_COND_INITIALIZER赋给静态分配的条件变量,但是如果条件变量是动态分配的,可以使用pthread_cond_destroy函数对条件变量进行去除初始化(deinitialize)。

  1. 创建及销毁条件变量
#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t cond);
// 返回:若成功返回0,否则返回错误编号

除非需要创建一个非默认属性的条件变量,否则pthread_cont_init函数的attr参数可以设置为NULL。

  1. 等待
#include <pthread.h>
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, cond struct timespec *restrict timeout);
// 返回:若成功返回0,否则返回错误编号

pthread_cond_wait等待条件变为真。如果在给定的时间内条件不能满足,那么会生成一个代表一个出错码的返回变量。传递给pthread_cond_wait的互斥量对条件进行保护,调用者把锁住的互斥量传给函数。函数把调用线程放到等待条件的线程列表上,然后对互斥量解锁,这两个操作都是原子操作。这样就关闭了条件检查和线程进入休眠状态等待条件改变这两个操作之间的时间通道,这样线程就不会错过条件的任何变化。pthread_cond_wait返回时,互斥量再次被锁住。
  
  pthread_cond_timedwait函数的工作方式与pthread_cond_wait函数类似,只是多了一个timeout。timeout指定了等待的时间,它是通过timespec结构指定。

  1. 触发
#include <pthread.h>
int pthread_cond_signal(pthread_cond_t cond);
int pthread_cond_broadcast(pthread_cond_t cond);
// 返回:若成功返回0,否则返回错误编号

这两个函数可以用于通知线程条件已经满足。pthread_cond_signal函数将唤醒等待该条件的某个线程,而pthread_cond_broadcast函数将唤醒等待该条件的所有进程。注意一定要在改变条件状态以后再给线程发信号。

代码示例

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

//int pthread_create(pthread_t *restrict tidp, const pthread_attr_t *restrict attr, void *(*start_rtn)(void *),
// void *restrict arg);
int g_data=0;

pthread_mutex_t mutex;
pthread_cond_t cond;
void *func1(void *arg)
{

  printf("t1:%ld thread is create\n",(unsigned long)pthread_self());
  printf("param is %d\n",*((int *)arg));

    while(1)
     {  
        pthread_cond_wait(&cond,&mutex);
        printf("t1  run =====================================================\n");
        printf("t1 :%d\n",g_data);
        g_data=0;
        sleep(1); 
     }
}

void *func2(void *arg)
{

  printf("t2:%ld thread is create\n",(unsigned long)pthread_self());
  printf("param is %d\n",*((int *)arg));
  while(1)
    { 
        printf("t2 :%d\n",g_data);
        pthread_mutex_lock(&mutex);
        g_data++;
          if(g_data == 3)
            {
                pthread_cond_signal(&cond);
            }
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}
 int main()
{
  
  int ret;
  int param=100;
  pthread_t t1;
  pthread_t t2;

  pthread_mutex_init(&mutex,NULL);
  pthread_cond_init(&cond,NULL);

  ret= pthread_create(&t1, NULL, func1,  (void *)&param);

  ret= pthread_create(&t2, NULL, func2,  (void *)&param);
 
  pthread_join(t1,NULL);
  pthread_join(t2,NULL);


  pthread_mutex_destroy(&mutex);
  pthread_cond_destroy(&cond); 


  return 0;
}

条件和互斥量的一次性初始化

     pthread_cond_t cond;
     //动态初始化: pthread_cond_init(&cond, NULL);
     //静态初始化: pthread_cond_t = PTHREAD_COND_INITIALIZER;
     pthread_mutex_t;
     //动态初始化: pthread_mutex_init(&mutex,NULL);
     //静态初始化: pthread_mutex_t = PTHREAD_MUTEX_INITIALIZER;

以上笔记参考与百度百科峰子——仰望阳光https://www.cnblogs.com/xiehongfeng100/p/4620852.html
师从上官可编程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Linux 下的线程接口是 POSIX 线程(pthread)库,它是一套标准的 API,定义了线程的创建、同步、通信等操作。下面绍一些常用的函数和操作: ### 线程创建 在 POSIX 线程库中,线程的创建使用 `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`:线程的入口函数,它必须是一个指向函数的指针,且返回类型为 `void *`,接受一个 `void *` 类型的参数。 - `arg`:传递给线程入口函数的参数。 `pthread_create` 函数成功时返回 0,否则返回错误码。 ### 线程等待 线程等待使用 `pthread_join` 函数,它的原型如下: ```c int pthread_join(pthread_t thread, void **retval); ``` 其中: - `thread`:线程标识符。 - `retval`:指向线程返回值的指针,如果不需要返回值,可以传递 `NULL`。 `pthread_join` 函数会阻塞当前线程,直到指定的线程退出并返回。如果线程已经被分离,或者已经退出,`pthread_join` 函数会立即返回,并且不会修改 `retval` 指向的值。`pthread_join` 函数成功时返回 0,否则返回错误码。 ### 线程分离 线程分离使用 `pthread_detach` 函数,它的原型如下: ```c int pthread_detach(pthread_t thread); ``` 其中: - `thread`:线程标识符。 `pthread_detach` 函数将指定的线程标记为分离状态,它的资源会在线程退出时自动被回收,无法再次被等待。如果一个线程已经被分离,再次调用 `pthread_detach` 函数会返回错误码。`pthread_detach` 函数成功时返回 0,否则返回错误码。 ### 线程取消 线程取消使用 `pthread_cancel` 函数,它的原型如下: ```c int pthread_cancel(pthread_t thread); ``` 其中: - `thread`:线程标识符。 `pthread_cancel` 函数向指定的线程发送一个取消请求,如果线程允许取消,它将会退出。线程可以通过设置取消状态和取消类型来控制取消的行为。`pthread_cancel` 函数成功时返回 0,否则返回错误码。 ### 线程同步 线程同步使用互斥锁、条件变量等机制来实现。这些机制可以通过 pthread 库提供的函数来使用,如 `pthread_mutex_init`、`pthread_mutex_lock`、`pthread_cond_init`、`pthread_cond_wait` 等等。这些函数的使用方法比较复杂,需要根据具体的应用场景来选择和使用。 以上是一些常用的 POSIX 线程库的函数和操作,使用时需要根据具体的业务需求进行选择和使用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值