首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。