首页 > 代码库 > thread_23

thread_23

//多线程链表添加删除例子(使用条件变量实现互斥): #include <stdlib.h>#include <pthread.h>#include <stdio.h>#include <sched.h>#include <string.h>typedef struct _list_head list_head;struct _list_head{       list_head *next;        list_head *prev;        int used;        int data; };list_head _head = {&_head, &_head, 0, 0};list_head *head = &_head;void list_add(list_head *entry, list_head *head){        head->next->prev = entry;        entry->next = head->next;        entry->prev = head;        head->next = entry; }  list_head *list_del(list_head *entry) {        entry->next->prev = entry->prev;        entry->prev->next = entry->next;        return entry; }pthread_cond_t cond;pthread_mutex_t lock; void *producer(void *arg) {         do{                list_head *node;                if(node = malloc(sizeof(list_head)) )                {                        memset((void *)node, \0, sizeof(list_head));                         node->data =http://www.mamicode.com/ rand();                }                else                        return NULL;               pthread_mutex_lock(&lock);                while(head->used != 0)                {                        pthread_cond_wait(&cond, &lock);                }                head->used = 1;                pthread_mutex_unlock(&lock);                list_add(node, head);                printf("product %d\n", node->data);                  head->used = 0;                 pthread_cond_signal(&cond);        }while(1); } void *consumer(void *arg) {         do{                 list_head *node;                pthread_mutex_lock(&lock);               while(head->used != 0 || head->next == head->prev)                {                         pthread_cond_wait(&cond, &lock);                 }                head->used = 1;                pthread_mutex_unlock(&lock);//这句代码一定要有,不然会发生死锁                 node = head->next;                 list_del(node);                  printf("consumer %d\n", node->data);                 free(node);                 head->used = 0;               pthread_cond_signal(&cond);         }while(1);} int main(int argc, char *argv[]) {        pthread_t  t1, t2;         int ret;        pthread_cond_init(&cond, NULL);        pthread_mutex_init(&lock, NULL);        pthread_create(&t1, NULL, producer, NULL);         pthread_create(&t2, NULL, consumer, NULL);          pthread_join(t1, NULL);        pthread_join(t2, NULL);          return 1; }//注意:最后两个join是必须的,否则主线程将提早结束,不会一直执行循环。/************pthread_cond_wait()的使用方法*********    pthread_mutex_lock(&qlock);        pthread_cond_wait(&qready, &qlock);    pthread_mutex_unlock(&qlock);*****************************************************/

 

thread_23