Pthread 互斥锁 Linux

Pthread Mutex Lock Linux

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

#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 在锁里面。我希望有人能让我理解我程序的这种行为。干杯!

call_time 是一个从 2 个线程访问的共享变量,因此必须加以保护。发生的事情是第一个线程启动,将 call_time 设置为 10 并打印第一个 round.Then 第二个线程启动,将 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;
}