线程(下)

这里写图片描述

条件变量:了解了生产者消费者模型,我们来假设这样一个场景:你去超时买泡面可是发现货架是空的,生产者并没有提供任何口味的泡面,为了避免让顾客傻等,就需要条件变量来帮助我们。当有货物来的时候会通知你“有面了,快来买”。

类比到线程,同样当一个线程访问队列时,发现队列为空,它只能等待,直到其它线程将一个节点添加到队列当中。

条件变量相关函数:
(1)初始化

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

cond:要初始化的条件变量
attr:NULL
(2)销毁条件变量

int pthread_cond_destroy(pthread_cond_t* cond);

(3)等待条件满足

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

第一个参数指向条件变量的指针,第二个参数指向互斥锁的指针。(为防止资源的竞争,条件变量总是和互斥锁协同使用)
(4)唤醒等待

int pthread_cond_broadcast(pthread_cond_t *cond);//唤醒集体
int pthread_cond_signal(pthread_cond_t *cond);//唤醒单个

利用单链表进行模拟生产者消费者场景
原理:利用两个线程来分别代表生产者和消费者,用单链表来表示中间的缓冲区

//创建节点结构
typedef struct ListNode
{
    int data;
    struct ListNode* _next;
}Node;
//构造节点
Node* creatNode(int data)
{
    Node* newNode = (Node*)malloc(sizeof(Node));
    if(newNode == NULL)
    {
        perror("malloc error\n");
        return NULL;
    }
    newNode->data = data;
    newNode->_next = NULL;
    return newNode;
}
//初始化
void InitList(Node** head)
{
    *head = creatNode(0);
}
//插入节点
void Push_head(Node* head,int data)
{
    assert(head);
    Node* newNode = creatNode(data);
    newNode->_next = head->_next;
    head->_next = newNode;
    return;
}
//判空
int IsEmpty(Node* head)
{
    assert(head);
    if(head->_next == NULL)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}
//删除节点
void DelNode(Node* del)
{
    assert(del);
    free(del);
    del = NULL;
    return;
}

void Pop_head(Node* head,int *data)
{
    assert(head);
    if(IsEmpty(head) != 0)
    {
        Node* del = head->_next;
        head->_next = del->_next;
        *data = del->data;
        DelNode(del);
        return;
    }
    printf("List if Empty!\n");
    return;
}
void DestroyList(Node* head)
{
    assert(head);
    Node* cur = head->_next;
    while(cur)
    {
        Pop_head(head,NULL);
        cur = cur->_next;
    }
    return;
}
//打印
void ShowList(Node* head)
{
    assert(head);
    Node* cur = head->_next;
    while(cur)
    {
        printf("%d ",cur->data);
        cur = cur->_next;
    }
    printf("\n");
    return;
}

当生产者生产数据时,将新的数据放入单链表的头部;

void thread_producer(void *arg)
{
    Node* head = (Node*)arg;
    while(1)
    {
        sleep(1);
        int data = rand()%100; //生成随机数
        pthread_mutex_lock(&mutex);//加锁
         Push_head(head,data);//放入数据
        pthread_mutex_unlock(&mutex);//解锁
        printf("Producer sell : %d\n",data);
        pthread_cond_signal(&cond);//唤醒等待
    }
      return NULL;
}   

当消费者消费数据时,将头部的数据弹出。

void* thread_consumer(void *arg)
{
    Node* head = (Node*)arg;
    while(1)
    {
        int data = 0;
        pthread_mutex_lock(&mutex);
        while(IsEmpty(head) == 0)//如果为空就等
        {
            pthread_cond_wait(&cond,&mutex);
        }
        Pop_head(head,&data);
        pthread_mutex_unlock(&mutex);
        printf("Consumer get : %d\n",data);
    }
    return NULL;
}

主函数:

int main()
{

    Node* head;
    InitList(&head);
    pthread_t tid1,tid2;
    pthread_create(&tid1,NULL,thread_producer,(void*)head);//创建生产者线程
    pthread_create(&tid2,NULL,thread_consumer,(void*)head);//创建消费者线程
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}

运行结果:生产者生产一个,消费者消费一个,实现同步

[a@localhost list]$ ./test
Producer sell : 83
Consumer get : 83
Producer sell : 86
Consumer get : 86
Producer sell : 77
Consumer get : 77
Producer sell : 15
Consumer get : 15

信号量:
信号量:
POSIX信号量和SysremV信号量作用相同,都是用于同步操作,达到无冲突的访问共享资源目的。但POSIX可以用于线程间同步。

(1)初始化

#include<semaphore.h>
int sem_init(sem_t *sem,int pshared,unsigned int value);

参数:pshared:0表示线程间共享,非零表示进程间共享
value:信号量初始值
(2)销毁信号量

int sem_destroy(sem_t *sem);

(3)等待信号量

int sem_wait(sem_t *sem);//会将信号量的值减1

(4)发布信号量

sem_post(sem_t *sem);//表示资源使用完了可以归还资源了

数组和模运算来模拟环状结构
可以用信号量来实现生产者消费者同步,在下图中环有6个格子可以存放数据,生产者p负责放数据,消费者c负责拿数据。这6个格子可以循环利用。可以把其想成一个环形队列。
生产者与消费者在环形队列下需要遵循以下规则:生产者优先,消费者的永远不能追上生产者,生产者也不能超过消费者一圈。(可以想象成两个人赛跑)
这里写图片描述
代码实现:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<time.h>
#include<semaphore.h>
#define M 32
int ring[M];
sem_t semBlank;//空白格信号量
sem_t semData;//数据信号量
void *runP(void *arg)
{
    int d;
    int i = 0;
    while(1)
    {
      sem_wait(&semBlank);//生产者等空白格子
      ring[i] = rand()%1234+1;//生成随机数
      i++;
      i%=M;
      printf("product done,data is:%d\n",d);
      sem_post(&semData);//生产者放数据
    }
}
void *runC(void *arg)
{
    int d;
    int i =0;
    while(1){
    sem_wait(&semData);//消费者等数据
        d = ring[i];
        i++;
        i%=M;
        printf("comsumer done,data is :%d\n",d);
        sem_post(&semBlank);//消费者拿走格子上数据 格子还原为空白。
        sleep(1);
    }
}
int main()
{
    sem_init(&semBlank,0,M);
    sem_init(&semData,0,0);
    srand((unsigned long)time(NULL));
    pthread_t t1,t2;
    pthread_create(&t1,NULL,runC,NULL);
    pthread_create(&t2,NULL,runP,NULL);
    sleep(1);
    sem_destroy(&semBlank);
    sem_destroy(&semData);
}

读写锁:
读写锁与互斥锁类似,不过读写锁允许更高的并行性。
读写锁的状态:(1)读模式下加锁状态(2)写模式下加锁状态(3)不加锁状态.
一次只有一个线程可以占有写模式的读写锁,但是多个线程可以同时占有读模式下的读写锁。
读写锁的行为:

这里写图片描述
读写锁也叫共享互斥锁,当读写锁是读模式锁住时,也认为是以共享模式锁住的,当它以写模式锁住时,可认为是以互斥模式锁住的。

读写锁在使用之前必须初始化,在释放他们底层内存之前必须销毁。
这里写图片描述
成功返回0,失败返回错误编号

要在读模式下锁定读写锁,需要调用pthread_rwlock_rdlock.
要在写模式下锁定读写锁,需要调用pthread_rwlock_wrlock.
不论在何种方式下锁住读写锁,都可以调用pthread_rwlock_wrlock.

pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);

代码实现读写锁:
这里写图片描述
主函数:

int main()
{
    pthread_rwlock_init(&rwlock,NULL);
    int i = 0;
    pthread_t t[8];
    for(;i<3;i++)
    {
      pthread_create(t+i,NULL,t_write,(void*)i);
    }
    for(;i<8;i++)
    {
      pthread_create(t+i,NULL,t_read,(void*)i);
    }
    for(i = 0;i < 8;i++)
    {
      pthread_join(t[i],NULL);
    }
    pthread_rwlock_destroy(&rwlock);
}

如主函数中所设计的,读写锁非常适合于对于数据结构读的次数远大于写次数的情况,5个线程读,接着3个线程写。
结果:
这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在多线程下注入 Spring Bean,我们需要注意一些问题。首先,Spring Bean 的依赖注入是线程安全的,因为 Spring 容器会保证 Bean 的实例唯一,并且在多线程环境中不会出现竞态条件。然而,如果我们在多线程环境下手动创建 Bean 实例并注入,就需要注意线程安全性。 为了在多线程下注入 Spring Bean,我们需要确保 Bean 的作用域是线程安全的。通常情况下,我们可以将 Bean 的作用域设置为 prototype,使得每个线程都拥有自己的 Bean 实例,避免线程间的竞态条件。 另外,我们需要注意在多线程环境下对 Bean 的操作是否会造成线程安全问题。比如在单例 Bean 中使用了非线程安全的对象或方法,就可能会导致线程安全问题。在这种情况下,我们需要使用同步机制来保证线程安全,或者考虑将 Bean 的作用域设置为 prototype。 在注入 Bean 的时候,我们还需要考虑是否需要进行依赖注入或者手动创建 Bean 实例。如果需要在多线程下注入 Bean,最好使用 Spring 容器进行依赖注入,这样可以保证线程安全性并且简化代码逻辑。 总的来说,在多线程下注入 Spring Bean,我们需要确保 Bean 的作用域是线程安全的,并且在操作 Bean 的过程中注意线程安全性,避免出现竞态条件。同时尽量使用 Spring 容器进行依赖注入,避免手动创建 Bean 实例造成线程安全问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值