linux多线程编程入门-同步机制-互斥量

来源:互联网 发布:机器码破解注册码软件 编辑:程序博客网 时间:2024/04/28 18:41

所谓同步,并不是日常用语中的同时进行的意思。这里的同步是指如何阻止同步进行的意思。

互斥量,又称互斥锁,它允许程序员锁住某个对象,使得每次只能有一个线程访问它。为了控制对关键代码的访问,必须在进入这段代码之前锁住一个互斥量,然后在完成操作之后解锁。


  加锁解锁成对出现。如果一个线程已加锁,而另一个线程试图加锁,则会阻塞在那里,直到第一个线程解锁,才继续往下执行。如果同一个线程连着两次加锁,则死锁,因为没有解锁。而解锁多加没有关系。

1 int pthread_mutex_init(pthread_mutex_t *mutex,const pthread_mutex_attr_t *mutexattr); mutex:互斥量对象。mutexattr:互斥量对象属性,默认NULL即可。
2 int pthread_mutex_lock(pthread_mutex *mutex);
3 int pthread_mutex_destroy(pthread_mutex *mutex);
4 int pthread_mutex_unlock(pthread_mutex *

一个非常简单的应用互斥锁的很直观的例子,如果去掉锁,则结果不同。这仅是一个简单的范例,在实际应用中,多线程对同一个元素的操作都需要加锁,否则总有概率会出现类似这个例子中 出现的问题,即使可以通过sleep手段撇脚的暂时避开。

#include <stdio.h>#include <unistd.h>#include <pthread.h>#include <stdlib.h>void * thread_fun1(void * arg);void * thread_fun2(void * arg);int a = 200;int b = 400;pthread_mutex_t work_mutex;int main(){pthread_t thread1, thread2;int res;res = pthread_mutex_init(&work_mutex, NULL);pthread_create(&thread1, NULL, thread_fun1, NULL);pthread_create(&thread2, NULL, thread_fun2, NULL);pthread_join(thread1, NULL);pthread_join(thread2, NULL);pthread_mutex_destroy(&work_mutex);exit(EXIT_SUCCESS);}void * thread_fun1(void * arg){pthread_mutex_lock(&work_mutex);a += 50;sleep(5);b -= 50;pthread_mutex_unlock(&work_mutex);}void * thread_fun2(void * arg){pthread_mutex_lock(&work_mutex);sleep(1);printf("a+b is %d\n", a+b);pthread_mutex_unlock(&work_mutex);}


原创粉丝点击