天天看點

pthread_mutex_init線程互斥鎖的使用

pthread_mutex_init

頭檔案:

#include <pthread.h>

函數原型:

int pthread_mutex_init(pthread_mutex_t *restrict_mutex,const pthread_mutexattr_t *restrict_attr);

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

示例對比

下面代碼是建立了兩個現象,線程1對全局變量gnum自增3次,線程2對其自增5次

1:未使用線程鎖得情況

/*************************************************************************
    > File Name: pthread.c
    > Author: kayshi
    > Mail: [email protected]
    > Created Time: Mon 21 Sep 2020 03:12:09 PM CST
 ************************************************************************/

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

int gnum = 0;

static void thread_fun1(void)
{
    int i = 0;
    for (i = 0; i < 3; i++)
    {   
        printf("this is  thread1\n");
        sleep(1);
        gnum++;
        printf("thread1 add  one to num %d\n", gnum);
    }   
}

static void thread_fun2(void)
{
    int i = 0;
    for (i = 0; i < 5; i++)
    {   
        printf("this is  thread2\n");
        sleep(1);
        gnum++;
        printf("thread2 add  one to num %d\n", gnum);
    }   
}

int main()
{
    pthread_t id1, id2;
    printf("start\n");
    pthread_create(&id1, NULL, (void *)thread_fun1, NULL);
    pthread_create(&id2, NULL, (void *)thread_fun2, NULL);
    pthread_join(id1, NULL);
    pthread_join(id2, NULL);
    printf("end\n");
}

           
pthread_mutex_init線程互斥鎖的使用

通過上面發現,線程1和線程2會交替着對全局變量遞增,屬于不可控制得狀态

2:添加線程鎖

/*************************************************************************
    > File Name: pthread.c
    > Author: kayshi
    > Mail: [email protected]
    > Created Time: Mon 21 Sep 2020 03:12:09 PM CST
 ************************************************************************/

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

int gnum = 0;
pthread_mutex_t mutex;

static void thread_fun1(void)
{
    int i = 0;
    for (i = 0; i < 3; i++)
    {   
        pthread_mutex_lock(&mutex);
        printf("this is  thread1\n");
        sleep(1);
        gnum++;
        printf("thread1 add  one to num %d\n", gnum);
        pthread_mutex_unlock(&mutex);
    }   
}

static void thread_fun2(void)
{
    int i = 0;
    for (i = 0; i < 5; i++)
    {   
        pthread_mutex_lock(&mutex);
        printf("this is  thread2\n");
        sleep(1);
        gnum++;
        printf("thread2 add  one to num %d\n", gnum);
        pthread_mutex_unlock(&mutex);
    }
}

int main()
{
    pthread_t id1, id2;
    printf("start\n");
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&id1, NULL, (void *)thread_fun1, NULL);
    pthread_create(&id2, NULL, (void *)thread_fun2, NULL);
    pthread_join(id1, NULL);
    pthread_join(id2, NULL);
    printf("end\n");
}

           
pthread_mutex_init線程互斥鎖的使用

通過上面得現象發現,線程2先對變量遞增,然後線程1再對變量遞增。

線程鎖得作用就在于,當一個線程擷取鎖執行後,另一個也需要獲得該鎖得線程就會阻塞等待這個鎖得釋放然後才能得以執行。

繼續閱讀