Linux学习之多线程编程(线程的同步)

言之者无罪,闻之者足以戒。 ——《诗序》

(三)、线程的同步

1、互斥量

当多个线程共享相同的内存时,需要每一个线程看到相同的视图。当一个线程修改变量时,而其他线程也可以读取或者修改这个变量,就需要对这些线程同步,确保他们不会访问到无效的变量。

在变量修改时间多于一个存储器访问周期的处理器结构中,当存储器的读和写这两个周期交叉时,这种潜在的不一致性就会出现。当然这与处理器相关,但是在可移植的程序中并不能对处理器做出任何假设。

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
//创建一个结构体,数据类型都一样是为了方便赋值
struct student
{
        int id;
        int age;
        int name;

}stu;
int i;

void *thread_fun1(void *arg)
{
        while(1)
        {
               //对结构体变量赋值
                stu.id = i;
                stu.age = i;
                stu.name = i;
                i++;
                if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
                {
                        printf("thread 1 %d,%d,%d\n", stu.id, stu.age, stu.name);
                        break;
                }
        }
        return (void *)0;
}
void *thread_fun2(void *arg)
{
        while(1)
        {
                stu.id = i;
                stu.age = i;
                stu.name = i;
                i++;
                if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
                {
                        printf("thread 2 %d,%d,%d\n", stu.id, stu.age, stu.name);
                        break;
                }
        }
        return (void *)0;
}
int main()
{
        pthread_t tid1,tid2;
        int err;
        //创建新的线程
        err = pthread_create(&tid1,NULL,thread_fun1,NULL);
        if(err != 0)
        {
                printf("create new thread failure\n");
                return;
        }
        err = pthread_create(&tid1,NULL,thread_fun1,NULL);
        if(err != 0)
        {
                printf("create new thread failure\n");
                return;
        }
        //等待新的线程运行结束
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);

        return 0;
}

为了让线程访问数据不产生冲突,这要就需要对变量加锁,使得同一时刻只有一个线程可以访问变量。互斥量本质就是锁,访问共享资源前对互斥量加锁,访问完成后解锁。

当互斥量加锁以后,其他所有需要访问该互斥量的线程都将阻塞。

当互斥量解锁以后,所有因为这个互斥量阻塞的线程都将变为就绪态,第一个获得cpu的线程会获得互斥量,变为运行态,而其他线程会继续变为阻塞,在这种方式下访问互斥量每次只有一个线程能向前执行。

互斥量用pthread_mutex_t类型的数据表示,在使用之前需要对互斥量初始化

1)、如果是动态分配的互斥量,可以调用pthread_mutex_init()函数初始化

2)、如果是静态分配的互斥量,还可以把它置为常量PTHREAD_MUTEX_INITIALIZER

3)、动态分配的互斥量在释放内存之前需要调用pthread_mutex_destroy()

(1)、pthread_mutex_init互斥量的初始化函数

int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr)

第一个参数:要初始化的互斥量

第二个参数:互斥量的属性(可以写NULL)

返回值:成功返回0,失败返回错误码

(2)、pthread_mutex_destory互斥量的销毁函数

int pthread_mutex_destory(pthread_mutex_t *mutex)

参数:要销毁的互斥量

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER(静态的方式);

(3)、pthread_mutex_lock加锁函数

 int pthread_mutex_lock(pthread_mutex_t *mutex)

参数:要加锁的互斥量

返回值:成功返回0,失败返回错误码

如果互斥量已经被锁住,那么会导致该线程阻塞。

(4)、pthread_mutex_trylock尝试加锁函数

 int pthread_mutex_trylock(pthread_mutex_t *mutex)

参数:要加锁的互斥量

返回值:成功返回0,失败返回错误码

如果互斥量已经被锁住,不会导致线程阻塞。

(5)、 pthread_mutex_unlock解锁函数

 int pthread_mutex_unlock(pthread_mutex_t *mutex)

参数:要解锁的互斥量

返回值:成功返回0,失败返回错误码

如果一个互斥量没有被锁住,那么解锁就会出错。

下面看一下代码:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>
//创建一个结构体,数据类型都一样是为了方便赋值
struct student
{
        int id;
        int age;
        int name;

}stu;
//定义两个全局变量,因为两个线程都要使用
int i;
pthread_mutex_t mutex;
void *thread_fun1(void *arg)
{
        while(1)
        {
                //加锁,对整个结构体访问进行加锁,防止产生错码
                pthread_mutex_lock(&mutex);
                stu.id = i;
                stu.age = i;
                stu.name = i;
                i++;
                if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
                {
                        printf("thread 1 %d,%d,%d\n", stu.id, stu.age, stu.name);
                        break;
                }
                //访问变量完成,需要进行解锁,只有这样其他线程才能访问
                pthread_mutex_unlock(&mutex);

        }

        return (void *)0;
}
void *thread_fun2(void *arg)
{

        while(1)
        {

                pthread_mutex_lock(&mutex);
                stu.id = i;
                stu.age = i;
                stu.name = i;
                i++;
                if(stu.id !=stu.age || stu.id !=stu.name || stu.age!=stu.name)
                {
                        printf("thread 2 %d,%d,%d\n", stu.id, stu.age, stu.name);
                        break;
                }

                pthread_mutex_unlock(&mutex);
        }
        return (void *)0;
}
int main()
{
        pthread_t tid1,tid2;
        int err;
        //对互斥量进行初始化,只有初始化过后互斥量才能使用
        err = pthread_mutex_init(&mutex,NULL);
        if(err != 0)
        {
                printf("init mutex failure\n");
                return ;
        }
        //创建新的线程
        err = pthread_create(&tid1,NULL,thread_fun1,NULL);
        if(err != 0)
        {
                printf("create new thread failure\n");
                return;
        }
        //创建新的线程
        err = pthread_create(&tid1,NULL,thread_fun1,NULL);
        if(err != 0)
        {
                printf("create new thread failure\n");
                return;
        }
        //等待新线程运行结束
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);

        return 0;
}

注意:加锁函数和解锁函数要成对的出现否则会出现错误。

2、读写锁

读写锁与互斥量类似,不过读写锁有更高的并行性。互斥量要么加锁要么不加锁,而且同一时刻只允许一个线程对其加锁。对于一个变量的读取,完全可以让多个线程同时进行操作。

变量类型:pthread_rwlock_t  *rwlock

读写锁有三种状态,读模式下加锁,写模式下加锁,不加锁。一次只有一个线程可以占有写模式下的读写锁但是多个线程可以同时占有读模式的读写锁。读写锁在写加锁状态时,在它被解锁之前,所有试图对这个锁加锁的线程都会阻塞。读写锁在读加锁状态时,所有试图以读模式对其加锁的线程都会获得访问权,但是如果线程希望以写模式对其加锁,它必须阻塞直到所有的线程释放锁

当读写锁以读模式加锁时,如果有线程试图以写模式对其加锁,那么读写锁会阻塞随后的读模式锁请求。这样可以避免读锁长期占用,而写锁达不到请求。(意思是如果现在处于读锁状态,有一个写锁发出请求,也有其他读锁发出请求,那么其他读锁会阻塞,写锁会执行)

读写锁非常适合对数据结构读次数大于写次数的程序,当它以读模式锁住时,是以共享的方式锁住的;当它以写模式锁住时,是以独占的模式锁住的。

(1)、pthread_rwlock_init读写锁初始化函数

 int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock,  const pthread_rwlockattr_t *restrict attr)

第一个参数:要初始化的锁

第二个参数:锁属性(可写NULL)

返回值:成功返回0,失败返回错误码

(2)、pthread_rwlpck_destory读写锁销毁函数

int pthread_rwlock_destroy(pthread_rwlock_t *rwlock)

参数:要销毁的锁

返回值:成功返回0,失败返回错误码

(3)、pthread_rwlock_rdlock读模式加锁

int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock)

参数:要加锁的锁

返回值:成功返回0,失败返回错误码

(4)、pthread_rwlock_tryrdlock尝试读模式加锁函数

int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock)

参数:要加锁的锁

返回值:成功返回0,失败返回错误码

(5)、pthread_rwlock_wrlock写模式加锁

int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock)

参数:要加锁的锁

返回值:成功返回0,失败返回错误码

(6)、pthread_rwlock_trywrlock尝试写模式加锁

int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock)

参数:要加锁的锁

返回值:成功返回0,失败返回错误码

(7)、pthread_rwlock_unlock解锁函数

int pthread_rwlock_unlock(pthread_rwlock_t *rwlock)

参数:要解锁的锁

返回值:成功返回0,失败返回错误码

下面来看一下程序:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>

//定义一个全局锁
pthread_rwlock_t rwlock;
int num=0;
void *thread_fun1(void *arg)
{
        //读加锁        
//      pthread_rwlock_rdlock(&rwlock);
        //写加锁
        pthread_rwlock_wrlock(&rwlock);
        printf("the first thread print %d\n",num);
        sleep(5);

        printf("the first thread over\n");
        //解锁
        pthread_rwlock_unlock(&rwlock);

        return (void *)1;
}
void *thread_fun2(void *arg)
{
        //读加锁        
//      pthread_rwlock_rdlock(&rwlock);
        //写加锁
        pthread_rwlock_wrlock(&rwlock);
        printf("the second thread print %d\n",num);
        sleep(5);

        printf("the second thread over\n");
        //解锁
        pthread_rwlock_unlock(&rwlock);

        return (void *)2;
}
int main()
{
        pthread_t tid1,tid2;
        int err;
        //初始化读写锁
        err=pthread_rwlock_init(&rwlock,NULL);
        if(err != 0)
        {
                printf("init rwlock failure\n");
                return;
        }
        //创建新的线程
        err=pthread_create(&tid1,NULL,thread_fun1,NULL);
        if(err != 0)
        {
                printf("create new firest thread failure\n");
                return;
        }
        err=pthread_create(&tid2,NULL,thread_fun2,NULL);
        if(err != 0)
        {
                printf("create new second thread failure\n");
                return;
        }
        //等待新线程执行完毕
        pthread_join(tid1,NULL);
        pthread_join(tid2,NULL);
        //读写锁的销毁
        pthread_rwlock_destroy(&rwlock);
        return 0;
}

3、条件变量

一个典型的实例
在一条生产先线上有一个仓库,当生产者生产的时候需要锁住仓库独占,而消费者取产品的时候也要锁住仓库独占。如果生产者发现仓库满了,那么他就不能生产了,变成了阻塞状态。但是此时由于生产者独占仓库,消费者又无法进入仓库去消耗产品,这样就造成了一个僵死状态。

我们需要一种机制,当互斥量被锁住以后发现当前线程还是无法完成自己的操作,那么它应该释放互斥量,让其他线程工作。

1)、可以采用轮询的方式,不停的查询你需要的条件

2)、让系统来帮你查询条件,使用条件变量pthread_cond_t cond

(1)、pthread_cond_init条件变量初始化函数

int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr)

第一个参数:要初始化的条件变量

第二个参数:条件变量属性(默认属性为NULL)

返回值:成功返回0,失败返回错误码

(2)、pthread_cond_destory条件变量销毁函数

int pthread_cond_destroy(pthread_cond_t *cond)

参数:要销毁的条件变量

返回值:成功返回0,失败返回错误码

(3)、 pthread_cond_wait等待条件变量被设置

 int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex)

第一个参数:要设置的条件变量

第二个参数:互斥量

返回值:成功返回0,失败返回错误码

(4)、pthread_cond_timedwait等待条件变量被设置(指定等待时间)

int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime)

第一个参数:要设置的条件变量

第二个参数:互斥量

第三个参数:等待的时间

返回值:成功返回0,失败返回错误码

时间用下面的结构体表示:

 struct timespec{
                   time_t tv_sec;
                   long tv_nsec;
              };

这个函数与pthread_cond_wait类似,只是多一个timeout,如果到了指定的时间条件还不满足,那么就返回。注意,这个时间是绝对时间。例如你要等待3分钟,就要把当前时间加上3分钟然后转换到 timespec,而不是直接将3分钟转换到 timespec

用来等待条件变量被设置,值得注意的是等待调用需要一个已经上锁的互斥体mutex,这是为了防止在真正进入等待状态之前别的线程有可能设置该条件变量而产生竞争。

当条件满足的时候,需要唤醒等待条件的线程

1)、pthread_cond_broadcast用于设置条件变量,即使得事件发生,这样等待该事件的线程将不再阻塞

 int pthread_cond_broadcast(pthread_cond_t *cond)

参数:条件变量

2)、pthread_cond_signal则用于解除某一个等待线程的阻塞状态

int pthread_cond_signal(pthread_cond_t *cond)

参数:条件变量

注意,一定要在条件改变以后在唤醒线程

下面来看一下程序:

首先看一下程序框架图:

程序代码:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <errno.h>

#define BUFFER_SIZE   5     //产品库存大小
#define PRODUCT_CNT   30    //产品生产总数

struct product_cons
{
        int buffer[BUFFER_SIZE];  //生产产品值
        pthread_mutex_t lock;   //互斥锁
        int readpos,writepos;   //读写位置
        pthread_cond_t notempty;//条件变量,非空
        pthread_cond_t notfull;//条件变量,非满
}buffer;

void init(struct product_cons *p)
{
        pthread_mutex_init(&p->lock,NULL);//互斥锁
        pthread_cond_init(&p->notempty,NULL);//条件变量
        pthread_cond_init(&p->notfull,NULL);//条件变量
        p->readpos = 0;
        p->writepos = 0;
}
void finish(struct product_cons *p)
{
        pthread_mutex_destroy(&p->lock);//销毁互斥锁
        pthread_cond_destroy(&p->notempty);//条件变量
        pthread_cond_destroy(&p->notfull);//条件变量
        p->readpos = 0;                 //读指针复位
        p->writepos = 0;                //写指针复位
}
//存储一个数据到buffer
void put(struct product_cons *p,int data)//输入餐产品子函数
{
        pthread_mutex_lock(&p->lock);
        if((p->writepos+1)%BUFFER_SIZE == p->readpos)
        {
                printf("producer wait for not full\n");
                pthread_cond_wait(&p->notfull,&p->lock);
        }

        p->buffer[p->writepos] = data;
        p->writepos++;
        if(p->writepos >= BUFFER_SIZE)
                p->writepos = 0;

        pthread_cond_signal(&p->notempty);
        pthread_mutex_unlock(&p->lock);
}
//读,从buffer移除一个数据
int get(struct product_cons *p)
{
        int data;
        pthread_mutex_lock(&p->lock);

        if(p->readpos == p->writepos)
        {
                printf("consumer wait for not empty\n");
                pthread_cond_wait(&p->notempty,&p->lock);
        }
        data=p->buffer[p->readpos];
        p->readpos++;
        if(p->readpos >=BUFFER_SIZE)
                p->readpos = 0;

        pthread_cond_signal(&p->notfull);
        pthread_mutex_unlock(&p->lock);

        return data;
}
void *producer(void *data)//子线程,生产
{
        int n;
        for(n=1;n<30;n++)
        {
                sleep(1);
                printf("put the %d product.....\n",n);
                put(&buffer,n);
                printf("put the %d protuct sucess\n",n);
        }

        printf("producer stopped\n");
        return NULL;
}
void *consumer(void *data)  //子线程,购买
{
        static int cnt = 0;
        int num;
        while(1)
        {
                sleep(2);
                printf("get  product ...\n");
                num = get(&buffer);
                printf("get the %d product success\n", num);
                if(++cnt == PRODUCT_CNT)
                        break;
        }

        printf("consumer stopped\n");
        return NULL;
}
int main(int argc, char *argv[])
{
        pthread_t th_a,th_b;
        void *retval;

        init(&buffer);

        pthread_create(&th_a, NULL, producer, 0);
        pthread_create(&th_b, NULL, consumer, 0);

        pthread_join(th_a, &retval);
        pthread_join(th_b, &retval);

        finish(&buffer);

        return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_42994525/article/details/83210598