线程的互斥:使用线程互斥锁
初始化锁
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
功能: 初始化互斥锁
参数:
mutex : 锁
attr : NULL 默认为互斥
返回值: 成功返回0
失败返回 error number 设置error
-
*》使用锁
-
#include <pthread.h>
-
int pthread_mutex_lock(pthread_mutex_t *mutex);
-
功能: 使用锁
-
参数:
-
mutex : 锁
-
返回值: 成功返回0
-
失败返回 error number 设置error
-
》解开锁
-
#include <pthread.h> int pthread_mutex_unlock(pthread_mutex_t
*mutex);
功能: 解开锁
参数: mutex : 锁
返回值: 成功返回0
失败返回 error number 设置error -
*》销毁锁
-
#include <pthread.h> int pthread_mutex_destroy(pthread_mutex_t *mutex);
-
功能: 销毁锁
-
参数:
-
mutex: 锁
返回值: 成功返回0
失败返回 error number 设置error
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>
int a;
int b;
pthread_mutex_t pmt;
void *show1(void *arg)
{
while(1){
printf("1\n");
pthread_mutex_lock(&pmt); //使用锁
a++,b++;
pthread_mutex_unlock(&pmt); //释放锁
}
pthread_exit(NULL);
return NULL;
}
void *show2(void *arg)
{
while(1){
printf("2\n");
pthread_mutex_lock(&pmt); //使用锁
if(a==b)
printf("a==b\n");
else
printf("a!=b\n");
pthread_mutex_unlock(&pmt); //释放锁
}
pthread_exit(NULL);
return NULL;
}
int main()
{
if(pthread_mutex_init(&pmt,NULL)){
perror("pthread_mutex_init error");
exit(-1);
}
///创建线程1
pthread_t thread1;
if(pthread_create(&thread1,NULL,show1,NULL)){
perror("pthread_create error");
exit(-1);
}
设置分离属性
if(pthread_detach(thread1)){
perror("pthread_detach error");
exit(-1);
}
///创建线程2
pthread_t thread2;
if(pthread_create(&thread2,NULL,show2,NULL)){
perror("pthread_create error");
exit(-1);
}
设置分离属性
if(pthread_detach(thread2)){
perror("pthread_detach error");
exit(-1);
}
while(1);
return 0;
}