linux下多线程编程原以及互锁、条件变量、读写锁、信号等通信机制

一、多线程编程

线程简单的说就是让多个函数同时执行,线程间通信是为了让他们有序的运行。

1.1创建一个线程就是执行一个函数。

                      线程                                                                                        进程

创建     pthread_create()                                                                    fork() ,vfork()

退出     pthread_exit()                                                                               exit()

等待     pthread_join()                                                                     wait(),waitpid()

取消     pthread_cancel()                                                                      abort()  

读取     pthread_self()                                                                           getpid()

通信机制:互斥锁、条件变量、读写锁、信号         无名管道、有名管道、信号、消息队列、

                                                                                                           信号量、共享内存

线程与私有数据创建:pthread_key_create()/pthread_key_detele()

读取线程私有数据:pthread_getspecific()/pthread_setspecific()

 

 

intpthread_create (pthread_t *__restrict __newthread,//新创建的线程ID

         __constpthread_attr_t *__restrict __attr,//线程属性

      void*(*__start_routine) (void *),//新创建的线程从start_routine开始执行

      void*__restrict __arg)//执行函数的参数,如果需要传入多个参数,需要使用一个包含这些参数的结构体地址。

 

1.2同步通信机制:互斥锁、条件变量、读写锁

1.2.1互斥锁

初始化互斥锁   pthread_mutex_init()

阻塞申请互斥锁pthread_mutex_lock()

释放互斥锁   pthread_mutex_unlock()

非阻塞申请互斥锁   pthread_mutex_trylock()

销毁互斥锁  pthread_mutex_destroy()

 

在使用互斥锁之前,要定义一个全局变量互斥锁,pthread_mutex_t  lock;

每个线程执行之前要先获得该互斥锁,避免另一个线程也执行。

1.2.2条件变量通信机制: 需和互斥锁一起使用

初始化条件变量                   pthread_cond_init()

阻塞等待条件变量        pthread_cond_wait()

通知等待条件的第一个线程pthread_cond_signal()

在指定的时间内阻塞等待条件变量pthread_cond_timewait()

通知等待该条件变量的所有线程  pthread_cond_broadcast()

销毁条件变量状态  pthread_cond_destroy()

在使用条件变量之前,要定义一个该条件变量(全局变量),pthread_mutex_condtion  condtion;

 

pthread_cond_signal()用于唤醒等待出现于条件变量condtion关联条件的第一个线程。

pthread_cond_wait(pthrea_cond_t*_restrict _cond, pthread_mutex_t *_restrict _mutex)阻塞等待条件变量,

 

1.2.3读写锁通信机制

(1)当前线程读数据,则允许其他线程执行读操作,但不允许写操作;

(2)当前线程写数据,则其他线程读、写操作均不可允许。

初始化读写锁                   pthread_rwlock_init()

阻塞申请读锁                        pthread_rwlock_rdlock()

非阻塞申请读锁                    pthread_rwlock_tryrdlock()

阻塞申请写锁                        pthread_rwlock_wrlock()

非阻塞申请写锁                    pthread_rwlock_trywrlock()

释放锁                                    pthread_rwlock_unlock()

销毁锁                                    pthread_rwlock_destroy()

1.3异步通信机制

1.3.1信号

线程信号管理:pthread_kill(),将信号发送给线程。在线程执行的函数中安装信号,当接受到信号的时候,就开始执行相关的代码。

 

 

3、条件变量条件变量用pthread_cond_t数据类型表示。条件变量本身由互斥量保护,所以在改变条件状态前必须锁住互斥量。
条件变量初始化:
第一种,赋值常量PTHREAD_COND_INITIALIZER;第二种,使用pthread_cond_init函数

int pthread_cond_init (pthread_cond_t *__restrict __cond,
   __const pthread_condattr_t *__restrict
   __cond_attr);int pthread_cond_destroy (pthread_cond_t *__cond);


条件等待
使用pthread_cond_wait等待条件为真。

 pthread_cond_wait (pthread_cond_t *__restrict __cond,
   pthread_mutex_t *__restrict __mutex)

这里需要注意的是,调用pthread_cond_wait传递的互斥量已锁定,pthread_cond_wait将调用线程放入等待条件的线程列表,然后释放互斥量,在pthread_cond_wait返回时,再次锁定互斥量。
唤醒线程
pthread_cond_signal唤醒等待该条件的某个线程,pthread_cond_broadcast唤醒等待该条件的所有线程。

int pthread_cond_signal (pthread_cond_t *__cond);
int pthread_cond_broadcast (pthread_cond_t *__cond)


来一个例子,主线程启动4个线程,每个线程有一个参数i(i=生成顺序),无论线程的启动顺序如何,执行顺序只能为,线程0、线程1、线程2、线程3。

 

 

#include <stdio.h>

#include <stdlib.h>

#include <pthread.h>

#include <unistd.h>

#include <string.h>

#define DEBUG 1

 

int num=0;

pthread_mutex_t mylock=PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t qready=PTHREAD_COND_INITIALIZER;

void * thread_func(void *arg)

{

  int i=(int)arg;

  int ret;

  sleep(5-i);//线程睡眠,然最先生成的线程,最后苏醒

  pthread_mutex_lock(&mylock);//调用pthread_cond_wait前,必须获得互斥锁

  while(i!=num)

  {

#ifdef DEBUG

    printf("thread %d waiting\n",i);

#endif

    ret=pthread_cond_wait(&qready,&mylock);//该函数把线程放入等待条件的线程列表,然后对互斥锁进行解锁,这两部都是原子操作。并且在pthread_cond_wait返回时,互斥量再次锁住。

    if(ret==0)

    {

#ifdef DEBUG

      printf("thread %d wait success\n",i);

#endif

    }else

    {

#ifdef DEBUG

      printf("thread %d wait failed:%s\n",i,strerror(ret));

#endif

    }

  }

  printf("thread %d is running \n",i);

  num++;

  pthread_mutex_unlock(&mylock);//解锁

  pthread_cond_broadcast(&qready);//唤醒等待该条件的所有线程

  return (void *)0;

}

int main(int argc, char** argv) {

  

  int i=0,err;

  pthread_t tid[4];

  void *tret;

  for(;i<4;i++)

  {

    err=pthread_create(&tid[i],NULL,thread_func,(void *)i);

    if(err!=0)

    {

      printf("thread_create error:%s\n",strerror(err));

      exit(-1);

    }

  }

  for (i = 0; i < 4; i++)

  {

    err = pthread_join(tid[i], &tret);

    if (err != 0)

    {

      printf("can not join with thread %d:%s\n", i,strerror(err));

      exit(-1);

    }

  }

  return 0;

}

 

编译线程程序时会警告说线程函数找不到

 pthread 库不是Linux系统默认的库,连接时需要使用静态库libpthread.a,所以在使用pthread_create()创建线程,以及调用pthread_atfork()函数建立fork处理程序时,需要链接该库。
问题解决:
   
在编译中要加-lpthread参数,thread.c为你些的源文件,不要忘了加上头文件#include<pthread.h>

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值