【工作笔记】互斥锁

来源:互联网 发布:java高级工程师技能树 编辑:程序博客网 时间:2024/06/10 01:35

代码说明

当代码中出现多个线程需要操作一个同一个变量时,需要互斥锁。下面的代码实现了,globVar增加200000次,一个线程增加10000次。互斥锁保证globVar是20000。代码在DEV C++上测试通过。


代码实例

#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <pthread.h>#include <semaphore.h>void *thread_function(void *arg);void *thread_function1(void *arg);void *thread_function2(void *arg);long long globVar = 0;pthread_t a_thread;pthread_t thread1;pthread_t thread2;/* 互斥锁 */pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;int main(){    int res = 0;    int *pRet;    /* 创建新线程1 */    res = pthread_create(&thread1, NULL, thread_function1, NULL);    if (res != 0)    {        perror("Thread creation failed");        exit(EXIT_FAILURE);    }    /* 创建新线程2 */    res = pthread_create(&thread2, NULL, thread_function1, NULL);    if (res != 0)    {        perror("Thread creation failed");        exit(EXIT_FAILURE);    }    /* 线程阻塞 */    pthread_join(thread1, &pRet);    pthread_join(thread2, &pRet);    /* 打印最后的globVar值 */    printf("globVar=%d", globVar);    return 0;}void *thread_function1(void *arg){    int i = 1;    int locVar=0;    for (i = 1; i <= 10000; i++)    {        /* 上锁 */        pthread_mutex_lock(&mtx);        globVar++;        /* 解锁 */        pthread_mutex_unlock(&mtx);    }}
0 0