线程同步与互斥

Linux--线程编程
多线程编程-互斥锁

线程同步与互斥

  1. 互斥锁
  2. 信号量
  3. 条件变量

互斥锁

#include 
    互斥锁静态初始化:pthread_mutex_t mtx=PTHREAD_MUTEX_INITIALIZER
   互斥动态锁初始化:pthread_mutex_init()
  互斥锁上锁:  pthread_mutex_lock()
  互斥锁判断上锁:pthread_mutex_trylock()
  互斥锁解锁:pthread_mutex_unlock()
  消除互斥锁:pthread_mutex_destroy()
 int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
 int pthread_mutex_lock(pthread_mutex_t *mutex);
 int pthread_mutex_unlock(pthread_mutex_t *mutex);
 int pthread_mutex_destroy(pthread_mutex_t *mutex);
线程同步与互斥_第1张图片
pthread_mutex_init()

互斥锁的基本使用

互斥量既可以像静态变量那样分配,也可以在运行时动态创建(例如,通过malloc()在一块内存中分配)。动态互斥量的创建稍微有些复杂。

#include 
#include 
#include 
#include 


void *thread1_fun(void*arg);

typedef struct arry_int
{
    int *a;
    int numb;
}ARRY_INT;

void reverse(int a[],int numb);

static pthread_mutex_t testlock;


int main(int argc, char const *argv[])
{
    pthread_t  thread1;
    pthread_mutex_init(&testlock, NULL);

    int a[20]={0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
    ARRY_INT a_int={a,sizeof(a)/sizeof(int)};

    //创建线程
    int ret=pthread_create(&thread1,NULL,thread1_fun,&a_int);
    if (ret!=0)
    {
        perror("pthread_create wrong");
        exit(EXIT_FAILURE);
    }

    while(1)
    {
        // 启动锁
        pthread_mutex_lock(&testlock);

        for (int i = 0; i < 20; ++i)
            printf("%d ",a[i]);
        // 解锁
        pthread_mutex_unlock(&testlock);
        printf("\n");
        sleep(1);

    }
    return 0;
}


void *thread1_fun(void*arg)
{
    ARRY_INT *a=(ARRY_INT*)arg;
    while(1)
    {
        pthread_mutex_lock(&testlock);
        reverse(a->a,a->numb);
        pthread_mutex_unlock(&testlock);
        sleep(1);
    }

    return NULL;
}



void reverse(int a[],int numb)
{
    int tem;
    for (int i = 0; i

信号量

       #include 

int sem_init(sem_t *sem, int pshared, unsigned int value);
创建一个信号量,并初始化它

  • sem:初始化一个信号量结构体在sem地址处
  • pshared:0为线程间共享信号量 1为进程间共享信号量 (但linux没有实现)
  • value:信号量的初始值

int sem_wait(sem_t *sem)  
int sem_trywait(sem_t *sem): P操作,在信号量大于零时将信号量的值减一   
区别: 若信号量小于零时,sem_wait()将会阻塞线程,sem_trywait()则会立即返回  

int sem_post(sem_t *sem): V操作,将信号量的值加一同时发出信号来唤醒等待的线程  

int sem_getvalue(sem_t *sem): 得到信号量的值  
int sem_destroy(sem_t *sem): 删除信号量

RETURN VALUE
All of these functions return 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate the error.

#include 
#include 
#include 
#include 

#define THREAD_NUM 3
#define REPEAT_TIMES 5
#define DELAY 4

sem_t sem[THREAD_NUM];

void *thrd_func(void *arg);

int main(){
    pthread_t thread[THREAD_NUM];
    int no;
    void *tret;
    
    srand((int)time(0)); 

    // 初始化THREAD_NUM-1个信号量,均初始化为0
    for(no=0;no

条件变量

你可能感兴趣的:(线程同步与互斥)