【工作笔记】互斥锁

代码说明

当代码中出现多个线程需要操作一个同一个变量时,需要互斥锁。下面的代码实现了,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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值