1.同步概念
2.线程同步:
同步同步调,对公共区域内容按照预定的先后次序访问,防止数据混乱。
线程同步,指一个线程发出某一功能调用时,在没有得到结果之前,该调用不返回。同时其他线程为保证数据一致性,不能调用该功能。
3.数据混乱原因
4.互斥量
linux中提供一把互斥锁mutex。
每个线程都在对资源操作前都能尝试加锁,成功加锁之后才能操作,操作结束解锁。
资源还是共享,线程间也还是竞争的。
当A线程对某个全局变量加锁访问,B在访问前尝试加锁,拿不到锁,B阻塞。C线程不去加锁,而直接访问该全局变量,依然能够访问,但会出现数据混乱。
所以,互斥锁实质上是操作系统提供的一把“建议锁”(又称“协同锁”)。
因此,即使有了MUTEX,如果有线程不按规则来访问数据,依然会造成数据混乱。
例程:父子进程共同使用共享资源stdout,利用sleep造成时间混乱,加锁进行共享资源控制。
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex;
void *tfn2(void *arg)
{
printf("如果大海能够换回曾经滴爱!\n");
}
void *tfn(void *arg)
{
srand(time(NULL));//随机函数
while(1)
{
int ret=pthread_mutex_lock(&mutex);
if(ret!=0)
{
fprintf(stderr,"pthread_mutex_lock() error:%s\n",strerror(ret));
}
printf("hello");
sleep(rand()%3);
printf("world\n");
ret=pthread_mutex_unlock(&mutex);
if(ret!=0)
{
fprintf(stderr,"pthread_mutex_unlock() error:%s\n",strerror(ret));
}
sleep(rand()%3);
}
return NULL;
}
int main(void)
{
pthread_t tid;
srand(time(NULL));//随机函数
int ret=pthread_mutex_init(&mutex,NULL);//初始化锁
if(ret!=0)
{
fprintf(stderr,"mutex init error:%s\n",strerror(ret));
}
//创建线程1
ret=pthread_create(&tid,NULL,tfn,NULL);//创建线程
if(ret!=0)
{
fprintf(stderr,"pthread_create error:%s\n",strerror(ret));
}
//创建线程2
ret=pthread_create(&tid,NULL,tfn2,NULL);
if(ret!=0)
{
fprintf(stderr,"pthread_create error:%s\n",strerror(ret));
}
while(1)
{
ret=pthread_mutex_lock(&mutex);//上锁
if(ret!=0)
{
fprintf(stderr,"mutex init error:%s\n",strerror(ret));
}
printf("HELLO");
sleep(rand()%3);
printf("WORLD\n");
ret=pthread_mutex_unlock(&mutex);//解锁
if(ret!=0)
{
fprintf(stderr,"pthread_mutex_unlock() error:%s\n",strerror(ret));
}
sleep(rand()%3);
}
pthread_join(tid,NULL);
ret=pthread_mutex_destroy(&mutex);
if(ret!=0)
{
fprintf(stderr,"pthread_mutex_destroy() error:%s\n",strerror(ret));
}
return 0;
}
运行结果:
线程2没有上锁,参与线程1与主线程的共享区域访问,造成混乱,文字“如果大海能够换回曾经滴爱”插入到了"HELLO"后面。
总结:写锁成功时后面所有访问都阻塞
读锁成功时后面写模式会阻塞
可以同时读,但不能同时写
例程:3个线程不定时写一全局资源,5个线程不定时读同一个全局资源
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int counter=0;
pthread_rwlock_t rwlock;
void *th_write(void *arg)
{
int t;
{
pthread_rwlock_wrlock(&rwlock);
t=counter;
pthread_rwlock_unlock(&rwlock);
usleep(1);
}
return NULL;
}
void *th_read(void *arg)
{
int i=(long int)arg,ret;
while(1)
{
ret=pthread_rwlock_rdlock(&rwlock);
printf("ret()=%d\n",ret);
pthread_rwlock_unlock(&rwlock);
usleep(100);
}
return NULL;
}
int main(void)
{
long int i;
pthread_t tid[8];
pthread_rwlock_init(&rwlock,NULL);
for(i=0;i<3;i++)
{
pthread_create(&tid[i],NULL,th_write,(void *)i);
}
for(i=0;i<5;i++)
{
pthread_create(&tid[i+3],NULL,th_read,(void *)i);
}
for(i=0;i<8;i++)
{
pthread_join(tid[i],NULL);
}
pthread_rwlock_destroy(&rwlock);
return 0;
}