Linux系统编程之线程同步

Linux系统编程之线程同步

一、线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作, 其他线程才能对该内存地址进行操作,而其他线程又处于等待状态,实现线程同步的方法有很多,临界区对象就是其中一种。

二、简介
在一般情况下,创建一个线程是不能提高程序的执行效率的,所以要创建多个线程。但是多个线程同时运行的时候可能调用线程函数,在多个线程同时对同一个内存地址进行写入,由于CPU时间调度上的问题,写入数据会被多次的覆盖,所以就要使线程同步。
同步就是协同步调,按预定的先后次序进行运行。如:你说完,我再说。
“同”字从字面上容易理解为一起动作
其实不是,“同”字应是指协同、协助、互相配合。
如进程、线程同步,可理解为进程或线程A和B一块配合,A执行到一定程度时要依靠B的某个结果,于是停下来,示意B运行;B依言执行,再将结果给A;A再继续操作。
所谓同步,就是在发出一个功能调用时,在没有得到结果之前,该调用就不返回,同时其它线程也不能调用这个方法。按照这个定义,其实绝大多数函数都是同步调用(例如sin, isdigit等)。但是一般而言,我们在说同步、异步的时候,特指那些需要其他部件协作或者需要一定时间完成的任务。例如Window API函数SendMessage。该函数发送一个消息给某个窗口,在对方处理完消息之前,这个函数不返回。当对方处理完毕以后,该函数才把消息处理函数所返回的LRESULT值返回给调用者。
在多线程编程里面,一些敏感数据不允许被多个线程同时访问,此时就使用同步访问技术,保证数据在任何时刻,最多有一个线程访问,以保证数据的完整性。

三、互斥锁(互斥量一般指互斥锁)
1.定义在编程中,引入了对象互斥锁的概念,来保证共享数据操作的完整性。每个对象都对应于一个可称为" 互斥锁" 的标记,这个标记用来保证在任一时刻,只能有一个线程访问该对象。

互斥变量是用pthread_mutex_t数据类型表示的。在使用互斥变量以前,必须首先对它进行初始化,可以把它设置为常量PTHREAD_MUTEX_INITALIZER(只适用于静态分配的互斥量),也可以通过调用pthread_mutex_init函数进行初始化。如果动态分配互斥量(例如,通过调用malloc函数),在释放内存前需要调用pthread_mutex_destroy。

2.创建和销毁互斥锁

#include <pthread.h>

int pthread_mutex_init(pthread_mutex_t restrict mutex,const
							 pthred_mutexattr_t *restrict attr);
int pthread_mutex_destroy(pthread_mutex *mutex);
		//两个函数返回值:若成功,返回0;否则,返回错误编码

①(动态方式)创建互斥锁: int pthread_mutex_init()
*mutex:定义的互斥锁。
*attr:要用默认的属性初始化互斥量,只需把attr设置为NULL。
②销毁互斥锁: int pthread_mutex_destroy
*mutex:定义的互斥锁。

3.加锁及解锁

#include <pthread.h>

int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
		//三个函数返回值:若成功,返回0;否则,返回错误编码

①pthread_mutex_lock():对互斥量进行加锁。
*mutex:定义的互斥锁。(下同)
②pthread_mutex_unlock():对互斥量解锁,如果互斥量已经上锁,调用线程将阻塞直到互斥量被解锁。
③pthread_mutex_trylock():如果不希望被阻塞,它可以使用此函数尝试对互斥量进行加锁。如果调用pthread_mutex_trylock时互斥量处于未锁住状态,那么pthread_mutex_trylock将锁住互斥量,不会出现阻塞直接返回0,否则pthread_mutex_trylock就会失败,不能锁住互斥量,返回EBUST。

实例1:

#include <pthread.h>
#include <stdio.h>

int g_data = 0;

pthread_mutex_t mutex;

void *func1(void *argv)
{
        pthread_mutex_lock(&mutex);
        int i;
        for(i=0;i<5;i++) {
                printf("t1: t1 thread is %ld\n",(unsigned long)pthread_self());
                printf("t1: param = %d,i = %d\n",*((int *)argv),i);
                sleep(1);
        }
        pthread_mutex_unlock(&mutex);
}

void *func2(void *argv)
{
        pthread_mutex_lock(&mutex);
        printf("t2: t2 thread is %ld\n",(unsigned long)pthread_self());
        printf("t2: param = %d\n",*((int *)argv));
        pthread_mutex_unlock(&mutex);
}

void *func3(void *argv)
{
        pthread_mutex_lock(&mutex);
        printf("t3: t3 thread is %ld\n",(unsigned long)pthread_self());
        printf("t3: param = %d\n",*((int *)argv));
        pthread_mutex_unlock(&mutex);
}

int main()
{
        pthread_t t1;
        pthread_t t2;
        pthread_t t3;
        int ret;
        int param = 100;
        int param2 = 200;
        int param3 = 300;

        pthread_mutex_init(&mutex,NULL);

        ret = pthread_create(&t1,NULL,func1,(void *)&param);
        if(ret == 0) {
                printf("main: create t1 succeed\n");
        }
        ret = pthread_create(&t2,NULL,func2,(void *)&param2);
        if(ret == 0) {
                printf("main: create t2 succeed\n");
        }
        ret = pthread_create(&t3,NULL,func3,(void *)&param3);
        if(ret == 0) {
                printf("main: create t3 succeed\n");
        }
        printf("main: main thread is %ld\n",(unsigned long)pthread_self());

        pthread_join(t1,NULL);
        pthread_join(t2,NULL);
        pthread_join(t3,NULL);

        pthread_mutex_destroy(&mutex);

        return 0;
}

运行结果:对互斥锁进行加锁后,任何其他试图再次对互斥锁加锁的线程将会被阻塞,直到锁被释放。对互斥锁进行加锁后,任何其他试图再次对互斥锁加锁的线程将会被阻塞,直到锁被释放。
在这里插入图片描述

实例2:互斥锁限制共享资源的访问

#include <pthread.h>
#include <stdio.h>

int g_data = 0;

pthread_mutex_t mutex;

void *func1(void *argv)
{
        printf("t1: t1 thread is %ld\n",(unsigned long)pthread_self());
        printf("t1: param = %d\n",*((int *)argv));
        pthread_mutex_lock(&mutex);
        while(1) {
                printf("t1:g_data=%d\n",g_data++);
                sleep(1);
                if(g_data == 3) {
                        pthread_mutex_unlock(&mutex);
                        printf("t1 quit ======================\n");
                        pthread_exit(NULL);
                }
        }
}

void *func2(void *argv)
{
        printf("t2: t2 thread is %ld\n",(unsigned long)pthread_self());
        printf("t2: param = %d\n",*((int *)argv));
        while(1) {
                printf("t2:g_data=%d\n",g_data);
                pthread_mutex_lock(&mutex);
                g_data++;
                pthread_mutex_unlock(&mutex);
                sleep(1);
        }
}

int main()
{
        pthread_t t1;
        pthread_t t2;
        int ret;
        int param = 100;
        int param2 = 200;

        pthread_mutex_init(&mutex,NULL);

        ret = pthread_create(&t1,NULL,func1,(void *)&param);
        if(ret == 0) {
                printf("main: create t1 succeed\n");
        }
        ret = pthread_create(&t2,NULL,func2,(void *)&param2);
        if(ret == 0) {
                printf("main: create t2 succeed\n");
        }
        printf("main: main thread is %ld\n",(unsigned long)pthread_self());

        while(1) {
                printf("main:g_data=%d\n",g_data);
                sleep(1);
        }

        pthread_join(t1,NULL);
        pthread_join(t2,NULL);

        pthread_mutex_destroy(&mutex);

        return 0;
}

运行结果如下:当g_data = 3 时,func1退出,也可以在func1种结束掉进程。
在这里插入图片描述
四、避免死锁:
如果线程试图对同一个互斥量加锁两次,那么它自身就会陷入死锁状态,但是使用互斥量时,还有其他不太明显的方法也能产生死锁。例如,程序中使用一个以上的互斥量时,如果允许一个线程一直占有第一个互斥量,并且在试图锁住第二个互斥量时存在阻塞状态,但是拥有第二个互斥量的线程也在试图锁住第一个互斥量。因为两个线程都在相互请求另一个线程拥有的资源,所以这两个线程都无法向前运行,于是就产生死锁。
解决方法:死锁预防、死锁避免、死锁检测和解除。

#include <pthread.h>
#include <stdio.h>

pthread_mutex_t mutex;
pthread_mutex_t mutex2;

void *func1(void *argv)
{
        int i;
        pthread_mutex_lock(&mutex);
        sleep(1);
        pthread_mutex_lock(&mutex2);
        for(i=0;i<5;i++) {
                printf("t1: t1 thread is %ld\n",(unsigned long)pthread_self());
                printf("t1: param = %d\n",*((int *)argv));
                sleep(1);
        }
        pthread_mutex_unlock(&mutex);
}

void *func2(void *argv)
{
        int i;
        pthread_mutex_lock(&mutex2);
        sleep(1);
        pthread_mutex_lock(&mutex);

        printf("t2: t2 thread is %ld\n",(unsigned long)pthread_self());
        printf("t2: param = %d\n",*((int *)argv));

        pthread_mutex_unlock(&mutex);
}

int main()
{
        pthread_t t1;
        pthread_t t2;
        int ret;
        int param = 100;
        int param2 = 200;

        pthread_mutex_init(&mutex,NULL);
        pthread_mutex_init(&mutex2,NULL);

        ret = pthread_create(&t1,NULL,func1,(void *)&param);
        if(ret == 0) {
                printf("main: create t1 succeed\n");
        }
        ret = pthread_create(&t2,NULL,func2,(void *)&param2);
        if(ret == 0) {
                printf("main: create t2 succeed\n");
        }
        printf("main: main thread is %ld\n",(unsigned long)pthread_self());

        pthread_join(t1,NULL);
        pthread_join(t2,NULL);

        pthread_mutex_destroy(&mutex);
        pthread_mutex_destroy(&mutex2);

        return 0;
}

运行结果:main卡住,t1,t1无法运行
在这里插入图片描述

五、条件变量
条件变量时线程可用的另一种同步机制。条件变量给多个线程提供了一个会和的场所。条件变量与互斥量一起使用时,允许线程以无竞争的方式等待特定的条件发生。
条件本身是由互斥量保护的。线程在改变条件状态之前必须首先锁住互斥量。其他线程在获得互斥量之前不会察觉到这种改变,因为互斥量必须在锁定以后才能计算条件。

1.创建和销毁条件变量:

#include <pthread.h>
int pthread_cond_init(pthread_cond_t *restrict cond,
						const pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);
				//两个函数返回值:若成功,返回0;否则返回错误编码

①创建条件:int pthread_cond_init()
*cond:定义的条件变量。
*attr:除非需要创建一个具有非默认属性的条件变量,否则将attr设置为NULL。
②销毁条件:int pthread_cond_destroy()
*cond:定义的条件变量。

2.等待:

#include <pthread.h>

int pthread_cond_wait(pthread_cond_t *restrict cond,
						pthread_mutex *restrict mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond,
							pthread_mutex *restrict mutex,
							const struct timespec *restrict tsptr);	
						//两个函数返回值:若成功,返回0;否则返回错误编码

①int pthread_cond_wait()
*cond:定义的条件变量。
*mutex:定义的互斥量。
②int pthread_cond_timedwait()函数的功能与pthread_cond_wait函数相似,只是多了一个超时(tsptr)。超时值指定了我们愿意等待多长时间,它是通过timespec结构指定的。

3.触发:

#include <pthread.h>

int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
	//两个函数返回值:若成功,返回0;否则返回错误编码

①int pthread_cond_signal()
*cond:定义的条件变量。
②int pthread_cond_signal()同上
①至少能唤醒一个等待该条件的线程,而②函数则能唤醒等待该条件的所有线程。

实例3:

#include <pthread.h>
#include <stdio.h>

int g_data = 0;

pthread_mutex_t mutex;
pthread_cond_t cond;

void *func1(void *argv)
{
        printf("t1: t1 thread is %ld\n",(unsigned long)pthread_self());
        printf("t1: param = %d\n",*((int *)argv));

        while(1) {
                pthread_cond_wait(&cond,&mutex);
                printf("t1 run =========================\n");
                printf("t1:g_data=%d\n",g_data);
                g_data = 0;
                sleep(1);
        }
}

void *func2(void *argv)
{
        printf("t2: t2 thread is %ld\n",(unsigned long)pthread_self());
        printf("t2: param = %d\n",*((int *)argv));
        while(1) {
                printf("t2:g_data=%d\n",g_data);
                pthread_mutex_lock(&mutex);
                g_data++;
                if(g_data == 3) {
                        pthread_cond_signal(&cond);
                }
                pthread_mutex_unlock(&mutex);
                sleep(1);
        }
}

int main()
{
        pthread_t t1;
        pthread_t t2;
        int ret;
        int param = 100;
        int param2 = 200;

        pthread_mutex_init(&mutex,NULL);
        pthread_cond_init(&cond,NULL);

        ret = pthread_create(&t1,NULL,func1,(void *)&param);
        if(ret == 0) {
                printf("main: create t1 succeed\n");
        }
        ret = pthread_create(&t2,NULL,func2,(void *)&param2);
        if(ret == 0) {
                printf("main: create t2 succeed\n");
        }
        printf("main: main thread is %ld\n",(unsigned long)pthread_self());

        printf("main:g_data=%d\n",g_data);

        pthread_join(t1,NULL);
        pthread_join(t2,NULL);

        pthread_mutex_destroy(&mutex);
        pthread_cond_destroy(&cond);

        return 0;
}

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值