日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

队列、函数-多线程 线程队列的实现-by小雨

發布時間:2025/3/15 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 队列、函数-多线程 线程队列的实现-by小雨 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

發一下牢騷和主題無關:

????考參他人的方法,自己做了簡略修改,現實一個通用的線程隊列。

????

#include <stdio.h> #include <pthread.h> #include <unistd.h>#define POOL_SIZE 10 #define QUEUE_LEN 20 pthread_mutex_t queue_lock; //隊列鎖 pthread_cond_t queue_cond; //條件量變int head = 0, tail = 0; int queue[QUEUE_LEN];void delay(int x) {int i,j;for(i = 0; i < x; i++)for(j = 0; j <x; j++); }void fun1(){printf("fun1 start\n");delay(1000);printf("fun1 end\n"); }void fun2(){printf("fun2 start\n");delay(2000);printf("fun2 end\n"); }void fun3(){printf("fun3 start\n");delay(3000);printf("fun3 end\n"); }void fun4(){printf("fun4 start\n");delay(4000);printf("fun4 end\n"); }int dequeue()//出對列函數 {int y;pthread_mutex_lock(&queue_lock);while(head == tail)//隊列中 無情求時,待等{pthread_cond_wait(&queue_cond, &queue_lock);//動自釋放鎖 }y = queue[++head];//需做循環處置 queue[head] is NULLif(head >= QUEUE_LEN)head = 0;pthread_mutex_unlock(&queue_lock);return y; }void * process_queue(void *arg) {int x = 0;for(;;){x = dequeue();printf("%d dequeue \n",x);switch(x){case 1:fun1(); break;case 2:fun2(); break;case 3:fun3(); break;default:fun4(); break;} } }int enqueue(int x)//插入求請 {int next;pthread_mutex_lock(&queue_lock);next = tail + 1;if(next >= QUEUE_LEN)next = 0;if(next == head){pthread_cond_signal(&queue_cond);//pthread_mutex_unlock(&queue_lock); return 0;// 示表隊列已滿}queue[next] = x;tail = next; pthread_cond_signal(&queue_cond);//激活pthread_mutex_unlock(&queue_lock);return 1;//入隊勝利 }int main() {int i;int num = 0;pthread_t tid[POOL_SIZE];pthread_mutex_init(&queue_lock, NULL);pthread_cond_init(&queue_cond, NULL);for(i = 0; i < POOL_SIZE; i++)pthread_create(&tid[i], NULL, process_queue, NULL);while(1){scanf("%d",&num);if(0 == num)// break;return 0;printf("%d ",num);while(!enqueue(num))//隊列滿時 待等{printf("queue is full\n");sleep(1);}}// for(i = 0; i < POOL_SIZE; i++) // pthread_join(tid[i], NULL);// pthread_mutex_destory(&queue_lock); // pthread_cond_destroy(&queue_cond);return 0; }

????還有一些不足之處,隨后補上。

????

????測試方法:

????鍵入 :

????4 3 2 1

????結果:
4 3 2 1 4 dequeue
fun4 start
3 dequeue
fun3 start
2 dequeue
fun2 start
1 dequeue
fun1 start
fun1 end
fun2 end
fun3 end
fun4 end

鍵入:

????0

????退出函數

文章結束給大家分享下程序員的一些笑話語錄: 古鴿是一種搜索隱禽,在中國快絕跡了…初步的研究表明,古鴿的離去,很可能導致另一種長著熊爪,酷似古鴿,卻又習性不同的猛禽類——犤毒鳥

總結

以上是生活随笔為你收集整理的队列、函数-多线程 线程队列的实现-by小雨的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。