同步:同步就是协同步调,按预定的先后次序进行运行。如:你说完,我再说。“同”字从字面上容易理解为一起动作,其实不是,“同”字应是指协同、协助、互相配合。
线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作, 其他线程才能对该内存地址进行操作,而其他线程又处于等待状态,目前实现线程同步的方法有很多,临界区对象就是其中一种。
实现线程同步的方法:
- 信号量 semaphore
- 互斥锁 mutex
信号量-同步实现
/*************************************************************************
> File Name: create.c
# File Name: create.c
# Author :彭敬
# QQ : 1964265813
# Email:1964265813@qq.com
# Blog:http://blog.csdn.net/ReturningProdigal
# Created Time: 2017年12月01日 星期五 11时27分08秒
************************************************************************/
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<semaphore.h>
int i, j;
sem_t sem_r;//同步读的信号量
sem_t sem_w;//同步写的信号量
void *fun(void *a){
while(1){
sem_wait(&sem_r);//申请对资源的读操作
printf("--child-- i: %d, j: %d\n", i, j);
usleep(1000);
sem_post(&sem_w);//释放对资源的写操作
}
return NULL;
}
int main(int argc, char *argv[])
{
int res = sem_init(&sem_r, 0, 1);//初始化读信号量
if(res != 0){
perror("sem_init read error");
return -1;
}
res = sem_init(&sem_w, 0, 0);//初始化写信号量
if(res != 0){
perror("sem_init write error");
return -1;
}
pthread_t thr1;
res = pthread_create(&thr1,NULL, fun, NULL);//线程创建
if(res != 0){
perror("create fail");
return -1;
}
int a = 0;
while(1){
sem_wait(&sem_w);//申请对资源的写操作
i = a;
j = a;
a++;
sem_post(&sem_r);//释放对资源的读操作
//usleep(100);
}
return 0;
}
互斥锁-同步实现
/*************************************************************************
> File Name: create.c
# File Name: create.c
# Author :彭敬
# QQ : 1964265813
# Email:1964265813@qq.com
# Blog:http://blog.csdn.net/ReturningProdigal
# Created Time: 2017年12月01日 星期五 11时27分08秒
************************************************************************/
#include<stdio.h>
#include<pthread.h>
#include<unistd.h>
#include<semaphore.h>
int i, j;
pthread_mutex_t mutex_r;
pthread_mutex_t mutex_w;
void *fun(void *a){
while(1){
pthread_mutex_lock(&mutex_w);//锁住写操作的互斥锁
printf("--child-- i: %d, j: %d\n", i, j);
sleep(1);
pthread_mutex_unlock(&mutex_r);//释放读操作的互斥锁
}
return NULL;
}
int main(int argc, char *argv[])
{
int res = pthread_mutex_init(&mutex_r, NULL);
if(res != 0){
perror("mutex_init read error");
return -1;
}
res = pthread_mutex_init(&mutex_w, NULL);
if(res != 0){
perror("mutex_init write error");
return -1;
}
pthread_t thr1;
res = pthread_create(&thr1,NULL, fun, NULL);
if(res != 0){
perror("create fail");
return -1;
}
int a = 0;
while(1){
pthread_mutex_lock(&mutex_r);//锁住读操作互斥锁
i = a;
j = a;
a++;
pthread_mutex_unlock(&mutex_w);//释放写操作互斥锁
}
return 0;
}