线程同步--条件变量
條件變量可以說是線程同步中運用最多的方式。最常見的是運用在消費者-生產者模型中。
一般由一個線程充當生產者,一個線程充當生產者。消費者需要等到足夠量的數據才來消耗數據。在這中間生產者產生數據,并在數據量足夠時發信號通知消費者取數據。
進程間的同步可以用信號量實現(sem_open時設置信號量初始值為0, sem_wait等待條件滿足,sem_post在條件滿足后發信號)
先寫一個簡單的sample來演示這個過程(用隊列中的代碼稍作修改)
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
typedef struct _ListNode{
struct _ListNode *prev;
struct _ListNode *next;
int data;
}ListNode;
typedef struct _List{
ListNode *head;
ListNode *tail;?
int len;
}List;
void list_init(List *pList)
{
pList->head = NULL;
pList->tail = NULL;
pList->len = 0;
}
void list_insert_tail(List *pList, ListNode *node)
{
? ? ? if (NULL == pList || NULL == node) return;
node->next = NULL;
if ((node->prev = pList->tail) != NULL)
{
pList->tail->next = node;
}
else
{
pList->head = node;
}
pList->tail = node;
pList->len++;
}
void list_remove(List *pList, ListNode* node)
{
if (pList->tail == node)
{
pList->tail = node->prev;
}
else
{
node->next->prev = node->prev;
}
if (pList->head == node)
{
pList->head = node->next;
}
else
{
node->prev->next = node->next;
}
if (node != NULL)
{
node->prev = node->next = NULL;
}
}
List _list;
pthread_mutex_t mutex;//最好的方式是將mutex和cond放到List結構體中。
pthread_cond_t cond;
void *produce_thread(void *param)
{
unsigned long data = 0;
printf("produce thread\n");
while(1)
{
ListNode *pListNode;
printf("produce data:%ld\n", data);
pListNode = (ListNode*)malloc(sizeof(ListNode));
pListNode->data = data++;
pListNode->prev = NULL;
pListNode->next = NULL;
pthread_mutex_lock(&mutex);
list_insert_tail(&_list,pListNode);
if (_list.len >= 10)//如果數據大于10個才發信號
{
pthread_cond_signal(&cond);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *consume_thread(void *param)
{
printf("consume thread\n");
while (1)
{
pthread_mutex_lock(&mutex);
while(_list.len < 10)//如果數據小于10個
{
printf("consume wait\n");
pthread_cond_wait(&cond, &mutex);//等待信號;先unlock前面的mutex,在收到signal后,重新lock上
printf("consume wait done\n");
int idx = 0;
ListNode *node;
for (idx = 0; idx < 10; idx++)
{
node = _list.head;
list_remove(&_list, node);
if(node)
{
printf("consume data: %d\n", node->data);
free(node);
node = NULL;
}
}
sleep(1);
}
pthread_mutex_unlock(&mutex);
}
}
int main(void)
{
list_init(&_list);
pthread_t tid_produce;
pthread_t tid_consume;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
printf("start thread\n");
pthread_create(&tid_produce, NULL, produce_thread, NULL);
pthread_create(&tid_consume, NULL, consume_thread, NULL);
while(1);
? ? ? pthread_mutex_destroy(&mutex);
? ? ? pthread_cond_destroy(&cond);
return 0;
}
?運行結果如下:
?
轉載于:https://www.cnblogs.com/fellow1988/p/6181374.html
總結
以上是生活随笔為你收集整理的线程同步--条件变量的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: codewars??? Is my fr
- 下一篇: 静态变量的陷阱