1.互斥锁的定义
互斥锁,是一种信号量,常用来防止两个进程或线程在同一时刻访问相同的共享资源。从本质上讲,互斥量是一把锁,该锁保护一个或者一些资源。一个线程如果需要访问该资源,必须要获得互斥量对其加锁。这时,如果其他线程想访问该资源也必须要获得该互斥量,但是锁已经加锁,所以这些进程只能阻塞,直到获得该锁的进程解锁。这时阻塞的线程里面有一个线程获得该互斥量并加锁,获准访问该资源,其他进程继续阻塞,周而复始。
2.互斥锁的初始化
Pthread_mutex_init函数
函数作用:用于初始化互斥锁
函数原型:int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);
参数:mutex:互斥锁
Attr:PTHREAD_MUTEX_INITIALIZER 创建快速互斥锁
PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP 创建递归互斥锁
PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP 创建检错互斥锁
返回值:成功返回0;出错返回-1
3.互斥锁操作的实现机制
下面是一个使用互斥锁的例子,在线程1和线程2中分别打印提示信息,通过使用互斥锁来控制线程1和线程2运行的先后顺序
- #include <stdio.h>
- #include <pthread.h>
- #include <stdlib.h>
-
- pthread_mutex_t mutex;
-
- void *thread1(void)
- {
- int i;
- pthread_mutex_lock(&mutex);
-
- for(i = 0; i < 4; i++)
- {
- printf("this is the 1st pthread\n");
- sleep(1);
- }
-
- pthread_mutex_unlock(&mutex);
- }
-
- void *thread2(void)
- {
- int i;
- pthread_mutex_lock(&mutex);
-
- for(i = 0; i < 4; i++)
- {
- printf("this is the 2nd pthread\n");
- sleep(1);
- }
-
- pthread_mutex_unlock(&mutex);
- }
-
- int main()
- {
- pthread_t id1,id2;
-
- if(pthread_mutex_init(&mutex,NULL) != 0)
- {
- printf("init failed!\n");
- exit(1);
- }
- if(pthread_create(&id1,NULL,(void *)thread1,NULL) != 0)
- {
- printf("create thread1 failed!\n");
- exit(1);
- }
- if(pthread_create(&id2,NULL,(void *)thread2,NULL) != 0)
- {
- printf("create thread2 failed!\n");
- exit(1);
- }
-
- pthread_join(id1,NULL);
- pthread_join(id2,NULL);
-
- sleep(1);
- return 0;
- }
二、信号量实现线程之间的PV操作,实现线程同步和互斥的数据模型?
1.sem_init函数
函数作用:初始化信号量
函数原型:int sem_init(sem_t *sem, int pshared, unsigned int value)
参数:sem:信号量指针
Pshared:决定信号量能否在几个进程间共享,一般取0
Value:信号量的初始值
2.信号的操作
Int sem_wait(sem_t *sem); P操作
Int sem_try_wait(sem_t *sem);
Int sempost(sem_t *sem); V操作
Int sem_getvalue(sem_t *sem);
Int sem_destroy(sem_t *sem); 销毁信号
3.用信号的PV操作来实现消费者和生产者的机制
- #include <stdio.h>
- #include <string.h>
- #include <pthread.h>
- #include <stdlib.h>
- #include <semaphore.h>
- #include <fcntl.h>
- #include <unistd.h>
- #include <sys/ipc.h>
-
- #define MAX_SIZE 1024
-
- sem_t sem1,sem2;
- char buff[MAX_SIZE];
-
- void producer(void *arg)
- {
- do
- {
- sem_wait(&sem1);
- printf("Producer enter some data:");
- scanf("%s",buff);
- sem_post(&sem2);
-
- }while(strncmp(buff,"quit",4) != 0);
- }
-
- void customer(void *arg)
- {
- do
- {
- sem_wait(&sem2);
- printf("Customer read is:%s\n",buff);
- sem_post(&sem1);
-
- }while(strncmp(buff,"quit",4) != 0);
- }
-
- int main()
- {
- pthread_t id1,id2;
-
- sem_init(&sem1,0,1);
- sem_init(&sem2,0,0);
-
- if(pthread_create(&id1,NULL,(void *)producer,NULL) != 0)
- {
- printf("init producer error!\n");
- return -1;
- }
- if(pthread_create(&id2,NULL,(void *)customer,NULL) != 0)
- {
- printf("init customer error!\n");
- return -1;
- }
-
- pthread_join(id1,NULL);
- pthread_join(id2,NULL);
-
- return 0;
- }