LINUX_C 線程總結(二)
話不多說,我們先來看一段代碼
/*************************************************************************
> File Name: condition.c
> Author:九五二七
> Mail:
> Created Time: 2017年08月02日 星期三 07時59分08秒
************************************************************************/
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
pthread_mutex_t mutex; //靜態
pthread_cond_t cond;
void *thread1(void *arg)
{
pthread_cleanup_push ((void *) pthread_mutex_unlock, &mutex); //pthread mutex unlock 爲指定函數
while (1){
printf ("thread1 is running \n");
pthread_mutex_unlock (&mutex);// 這個mutex主要是用來保證pthread_cond_wait的併發性
pthread_cond_wait (&cond , &mutex);// pthread_cond_wait會先解除之前的pthread_mutex_lock鎖定的mtx,然後阻塞在等待對列裏休眠,直到再次被喚醒(大多數情況下是等待的條件成立而被喚醒,喚醒後,該進程會先鎖定先pthread_mutex_lock(&mtx);,再讀取資源, 用這個流程是比較清楚的/*block-->unlock-->wait() return-->lock*/
printf ("thread1 applied the condition\n ");
pthread_mutex_unlock (&mutex);
sleep(4);
}
pthread_cleanup_pop(0); //當執行到這一步時返回 push 釋放指定資源
}
void *thread2(void *arg)
{
while (1){
printf ("thread2 is running \n");
pthread_mutex_unlock (&mutex);
pthread_cond_wait (&cond , &mutex);
printf ("thread2 applied the condition\n ");
pthread_mutex_unlock (&mutex);
sleep(1);
}
}
int main(){
pthread_t tid1,tid2;
printf("condition variable study !\n");
pthread_mutex_init (&mutex, NULL);//鎖的初始化
pthread_cond_init (&cond , NULL); //條件變量的初始化
pthread_create (&tid1, NULL, (void *)thread1, NULL);//實踐證明線程1與線程2無特定先後順序
pthread_create (&tid2, NULL, (void *)thread2, NULL);
do{
pthread_cond_signal(&cond); // 用於激活條件變量 併發出信號 由wait所指定的變量來接收
} while (1);
sleep(50);
pthread_exit(0);
}
這裏用到了鎖和條件變量這兩種手段
加鎖和解鎖
#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);
用此函數起作用可以相當於一個宏觀上的原子操作
即假如有一個變量需要操作lock會進行阻塞第二線程不會對此變量進行操作,即可以在宏觀上可以看做是一個原子操作
鎖用完是需要清除的
條件變量
等待天劍變量的成立
“““
int pthread_cond_timedwait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex,const struct timespec *restrict abstime);
int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);
>.激活條件變量