linux线程互斥锁的使用方法及代码测试

2025-10-17 01:12:04

1、编辑调试代码

#include <stdio.h>

#include <pthread.h>

int global_val = 0;

void *thread1(void *arg){

        while(1){

                global_val = global_val + 1;

                printf("thread1 global_val=%d\n", global_val);

                global_val = global_val + 1;

                usleep(100);

                printf("thread1 global_val=%d\n", global_val);

                usleep(100);

        }

        return NULL;

}

void *thread2(void *arg){

        while(1){

                global_val = global_val + 1;

                printf("thread2 global_val=%d\n", global_val);

                usleep(100);

                global_val = global_val + 1;

                printf("thread2 global_val=%d\n", global_val);

                usleep(100);

        }

        return NULL;

}

linux线程互斥锁的使用方法及代码测试

2、编译测试代码gcc mutex.c -o mutex -lpthread

linux线程互斥锁的使用方法及代码测试

3、查看运行结果,图示位置发现问题。结果不正确。

linux线程互斥锁的使用方法及代码测试

4、上述代码是无锁状态下的运行情况,运行结果与预期的结果不同,出现错误。下面我们加上互斥锁。

#include <stdio.h>

#include <pthread.h>

pthread_mutex_t thread_mutex;

int global_val = 0;

void *thread1(void *arg){

while(1){

pthread_mutex_lock(&thread_mutex);

global_val = global_val + 1;

printf("thread1 global_val=%d\n", global_val);

global_val = global_val + 1;

usleep(100);

                printf("thread1 global_val=%d\n", global_val);

usleep(100);

pthread_mutex_unlock(&thread_mutex);

}

return NULL;

}

void *thread2(void *arg){

while(1){

pthread_mutex_lock(&thread_mutex);

        global_val = global_val + 1;

        printf("thread2 global_val=%d\n", global_val);

                usleep(100);

global_val = global_val + 1;

                printf("thread2 global_val=%d\n", global_val);

        usleep(100);

pthread_mutex_unlock(&thread_mutex);

}

return NULL;

}

int main(void){

pthread_t thread_id1 = 0, thread_id2 = 0;

pthread_mutex_init(&thread_mutex, NULL);

pthread_create(&thread_id1, NULL, thread1, NULL);

pthread_create(&thread_id2, NULL, thread2, NULL);

pthread_join(thread_id1, NULL);

pthread_join(thread_id2, NULL);

return 0;

}

linux线程互斥锁的使用方法及代码测试

5、保存代码后编译。

linux线程互斥锁的使用方法及代码测试

6、运行查看结果,与预期的一致。说明互斥锁起到保护临界资源的作用。

linux线程互斥锁的使用方法及代码测试

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢