pthread 線程鎖和條件鎖


靜態初始化互斥鎖,方法如下: pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;

動態方式是采用pthread_mutex_init()函數來初始化互斥鎖,API定義如下:   int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr)

pthread_mutex_lock( pthread_mutex_t *mutex) :

pthread_mutex_unlock( pthread_mutex_t *mutex);

pthread_mutex_trylock( pthread_mutex_t *mutex);  非阻塞調用模式

int pthread_join(pthread_t thread, void **retval); 線程阻塞函數

void pthread_exit(void *retval); 結束現場返回 ,通過retval

 

條件鎖:

pthread_cond_t condmutex = PTHREAD_COND_INITIALIZER;

pthread_cond_wait( &condmutex, &mutex);   此函數是阻塞函數,調用前后鎖都是鎖住的,阻塞過程中函數會打開鎖,

  pthread_cond_signal(&cond); 發送信號前鎖必須是開的,否則無法跳出阻塞。

/*
 * 1p.c
 *
 *  Created on: Jan 18, 2017
 *      Author: s
 */

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

#include <pthread.h>

    unsigned count = 0;
    pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t  cond = PTHREAD_COND_INITIALIZER;

void decrement_count() {
    pthread_mutex_lock (&count_lock);
    sleep(1);
    //while(count==0)
        pthread_cond_wait( &cond, &count_lock);

    count=count -1;
    pthread_mutex_unlock (&count_lock);
    printf("decrement done,count = %d\n",count);
}

void increment_count(){
    pthread_mutex_lock(&count_lock);

    if(count==0)
       // pthread_cond_signal(&cond);

    count=count+1;
    pthread_mutex_unlock(&count_lock);
    printf("increment done.count = %d\n",count);
}
void test()
{
    sleep(5);
    pthread_mutex_lock(&count_lock);

    printf("sleep 5s \n");
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&count_lock);
}

int main()
{


    pthread_t idone,idtwo,id3;
    int ret;
    ret=pthread_create(&idone,NULL,(void *) decrement_count,NULL);
    if(ret!=0){
    printf ("Create pthread 1 error!/n");
    exit (1);
    }

    ret=pthread_create(&idtwo,NULL,(void *) increment_count,NULL);
    if(ret!=0){
    printf ("Create pthread 2 error!/n");
    exit (1);
    }

    ret=pthread_create(&id3,NULL,(void *) test,NULL);
    if(ret!=0){
    printf ("Create pthread 3 error!/n");
    exit (1);
    }

    printf("count = %d\n",count);
    printf(" exec: pthread_join(idone,NULL); \n ");
    pthread_join(idone,NULL);
    pthread_join(idtwo,NULL);
    pthread_join(id3,NULL);

    printf("done\n");
    return 0;
}

 

 

對共享資源操作前一定要獲得鎖.

完成操作以后一定要釋放鎖.

盡量短時間地占用鎖.

如果有多鎖, 如獲得順序是ABC連環扣, 釋放順序也應該是ABC.

線程錯誤返回時應該釋放它所獲得的鎖


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM