3

线程同步

 2 years ago
source link: https://blog.51cto.com/u_15515702/5259939
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

线程同步_五个板栗的技术博客_51CTO博客

五个板栗 2022-04-28 20:03:06 ©著作权

文章标签 线程同步 加锁 解锁 共享资源 文章分类 Linux 系统/运维 阅读数181

一、线程同步的概念

       在日常生活中,我们常常把”同步“理解为共同起步,一起动作,而线程同步中”同步“的是指协同步调,按照预定的先后次序运行。                                     线程同步:一个线程发出某一功能调用时,在没有得到相应的结果之前,此次调用不返回,同时其他线程为了保证数据的一致性,不能调用该功能。

二、线程同步的必要性

       在资源共享和调度随机不可能改变的情况下,只有设置线程同步,才能避免数据不发生混乱。

三、实现同步

       Linux中提供了互斥变量mutex,也称为互斥锁,来实现线程间的同步。当每个线程对共享资源进行操作之前,都要先对共享资源进行加锁操作,成功加锁之后才能对共享资源进行操作,在这个操作过程中,其他线程无法操作,操作结束后解锁,其他线程才可以再进行加锁和操作。

线程同步_线程同步

举个例子:主进程和子进程同时访问屏幕,我们发现输出并不是按照我们想象的那样,出现了数据混乱的现象。

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
void *test(void *arg)
{
srand(time(NULL));
while(1){
printf("hello");
sleep(rand()%3);
printf("world\n");
}
return NULL;
}
int main()
{
pthread_t t;
srand(time(NULL));
pthread_create(&t,NULL,test,NULL);
while(1){
printf("hi");
sleep(rand()%3);
printf("bye\n");
sleep(rand()%3);
}
}

线程同步_线程同步_02

进程同步函数

int pthread_mutex_init(pthread_mutex_t *mutex,
const pthread_mutexattr_t *mutexattr);
//初始化锁pthread_mutex_t 是一个结构体,返回值:成功返回0,失败返回错误码
int pthread_mutex_lock(pthread_mutex_t *mutex);
//加锁
int pthread_mutex_trylock(pthread_mutex_t *mutex);
//
int pthread_mutex_unlock(pthread_mutex_t *mutex);
//解锁
int pthread_mutex_destroy(pthread_mutex_t *mutex);
//销毁锁

解决上面例子中出现的问题

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
pthread_mutex_t mutex;//定义互斥锁
void *test(void *arg)
{
srand(time(NULL));
while(1){
pthread_mutex_lock(&mutex);//加锁
printf("hello");
sleep(rand()%3);
printf("world\n");
pthread_mutex_unlock(&mutex);
sleep(rand()%3);
}
return NULL;
}
int main()
{
pthread_t t;
srand(time(NULL));
int mid=pthread_mutex_init(&mutex,NULL);
if(mid!=0)
{
fprintf(stderr,"mutex init error:%s\n",strerror(mid));
exit(1);
}
pthread_create(&t,NULL,test,NULL);
while(1){
pthread_mutex_lock(&mutex);
printf("hi");
sleep(rand()%3);
printf("bye\n");
pthread_mutex_unlock(&mutex);
sleep(rand()%3);
}
pthread_join(t,NULL);
pthread_mutex_destroy(&mutex);
return 0;
}

线程同步_加锁_03


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK