码迷,mamicode.com
首页 > 编程语言 > 详细

线程同步

时间:2020-06-13 00:08:25      阅读:67      评论:0      收藏:0      [点我收藏+]

标签:lap   show   bsp   max   失败   线程   pre   str   click   

互斥锁(互斥量)

创建互斥锁

pthread_mutex_t mutex;

初始化互斥锁

pthread_mutex_init(pthread_mutex_t* mutex,
  const pthread_mutexattr_t* attr
);

销毁互斥锁

pthread_mutex_unlock(pthread_mutex_t *mutex);

加锁

//如果加锁的时候发现锁已经被锁上了,线程会一直阻塞在这个位置
pthread_mutex_lock(pthread_mutex_t *mutex);

//尝试加锁,失败返回,不阻塞
pthread_mutex_trylock(pthread_mutex_t *mutex);

解锁

pthread_mutex_unlock(pthread_mutex_t *mutex);

实例

技术图片
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>

#define MAX 10000

int number;

//创建一把互斥锁
pthread_mutex_t mutex;

void* funcA_num(void* arg)
{
        int i;
        for(i=0; i<MAX; i++)
        {
                //加锁
                pthread_mutex_lock(&mutex);
                int cur = number;
                cur++;
                number = cur;
                printf("Thread A, id = %lu, number = %d\n", pthread_self(), number);
                //解锁
                pthread_mutex_unlock(&mutex);
                usleep(10);
        }

        return NULL;
}

void* funcB_num(void* arg)
{
        int i;
        for(i=0; i<MAX; i++)
        {
                //加锁
                pthread_mutex_lock(&mutex);
                int cur = number;
                cur++;
                number = cur;
                printf("Thread B, id = %lu, number = %d\n", 
pthread_self(), number);
                //解锁
                pthread_mutex_unlock(&mutex);
                usleep(10);
        }

        return NULL;
}

int main(int argc, const char* argv[])
{
        pthread_t p1, p2;

        //初始化互斥锁
        pthread_mutex_init(&mutex, NULL);

        //创建两个子进程
        pthread_create(&p1, NULL, funcA_num, NULL);
        pthread_create(&p2, NULL, funcB_num, NULL);

        //阻塞,回收资源
        pthread_join(p1, NULL);
        pthread_join(p2, NULL);

        //释放互斥锁资源
        pthread_mutex_destroy(&mutex);

        return 0;
}
View Code

 

线程同步

标签:lap   show   bsp   max   失败   线程   pre   str   click   

原文地址:https://www.cnblogs.com/xumaomao/p/13110990.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!