Pthread Mutex Lock Linux

时间:2016-02-01 07:42:30

标签: linux multithreading pthreads mutex

我创建了一个简单的程序,显示了互斥锁的使用。这是代码......

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define NUM_THREAD 2

pthread_mutex_t mutex;
int call_time;

void *makeCall(void *param)
{
    call_time = 10;

    pthread_mutex_lock(&mutex);

        printf("Hi I'm thread #%u making a call\n", (unsigned int) pthread_self());
        do{
            printf("%d\n", call_time);
            call_time--;
            sleep(1);
        }
        while(call_time > 0);

    pthread_mutex_unlock(&mutex);

    return 0;
}

int main()
{

    int i; 
    pthread_t thread[NUM_THREAD];
    //init mutex
    pthread_mutex_init(&mutex, NULL);
    //create thread
    for(i = 0; i < NUM_THREAD; i++)
        pthread_create(&thread[i], NULL, makeCall, NULL);
    //join thread
    for(i = 0; i < NUM_THREAD; i++)
        pthread_join(thread[i], NULL);

    pthread_mutex_destroy(&mutex);
    return 0;
}

输出是......

Hi I'm thread #3404384000 making a call
10
10
9
8  
7
6
5
4
3
2
1
Hi I'm thread #3412776704 making a call
0

但是,如果我修改函数 makeCall 并在互斥锁内传递变量 call_time ...

pthread_mutex_lock(&mutex);
    call_time = 10;
    /*
     * 
     *
     *
     */
pthread_mutex_unlock(&mutex);

程序现在给我正确的输出,其中每个线程从10减少到0。我不理解它在锁内传递变量 call_time 的区别。我希望有人能让我理解我的程序的这种行为。干杯!

1 个答案:

答案 0 :(得分:1)

call_time是一个共享变量,可以从2个线程访问,因此必须受到保护。发生的事情是第一个线程开始,将call_time设置为10并打印第一轮。然后第二个线程启动,将call_time重置为10并等待互斥锁。第一个线程现在返回并继续运行,call_time重置为10.完成并释放互斥锁后,第二个线程现在可以运行。 call_time现在为0,因为第一个线程将其保留为0,因此它只打印最后一轮。

尝试这个程序,我认为它会更好地演示线程:

#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#define NUM_THREAD 2

pthread_mutex_t mutex;
int call_time;

void *makeCall(void *param)
{
    int temp;
    do{
        pthread_mutex_lock(&mutex);
        printf("Hi I'm thread #%u making a call\n", (unsigned int) pthread_self());
        printf("%d\n", call_time);
        temp = call_time--;
        pthread_mutex_unlock(&mutex);
        //sleep(1); //try with and without this line and see the difference.
    }
    while(temp > 0);

    return 0;
}

int main()
{
    int i; 
    call_time = 100;
    pthread_t thread[NUM_THREAD];
    //init mutex
    pthread_mutex_init(&mutex, NULL);
    //create thread
    for(i = 0; i < NUM_THREAD; i++)
        pthread_create(&thread[i], NULL, makeCall, NULL);
    //join thread
    for(i = 0; i < NUM_THREAD; i++)
        pthread_join(thread[i], NULL);

    pthread_mutex_destroy(&mutex);
    return 0;
}