#include <stdio.h>\n#include <stdlib.h>\n#include <pthread.h>\n#include <windows.h>\ntypedef struct QueueNode {\n int id;\n struct QueueNode* next;\n}QueueNode;\ntypedef struct TaskQueue {\n QueueNode* front;\n QueueNode* rear;\n}TaskQueue;\nint InitQueue(TaskQueue* Qp) {\n Qp->rear = Qp->front = (QueueNode*)malloc(sizeof(QueueNode));\n Qp->front->id = 2018;\n Qp->front->next = NULL;\n return 1;\n}\nint EnQueue(TaskQueue* Qp, int e) {\n QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));\n if (newnode == NULL)\n return 0;\n newnode->id = e;\n newnode->next = NULL;\n Qp->rear->next = newnode;\n Qp->rear = newnode;\n return 1;\n}\nint DeQueue(TaskQueue* Qp, int* ep, int threadID) {\n QueueNode* deletenode;\n if (Qp->rear == Qp->front)\n return 0;\n deletenode = Qp->front->next;\n if (deletenode == NULL) {\n return 0;\n }\n ep = deletenode->id;\n Qp->front->next = deletenode->next;\n free(deletenode);\n return 1;\n}\nint GetNextTask();\nint thread_count, finished = 0;\npthread_mutex_t mutex, mutex2;\npthread_cond_t cond;\nvoid task(void* rank);\nTaskQueue Q;\nint main()\n{\n int n;\n InitQueue(&Q);\n pthread_t* thread_handles;\n thread_count = 8;\n thread_handles = malloc(thread_count * sizeof(pthread_t));\n pthread_mutex_init(&mutex, NULL);\n pthread_mutex_init(&mutex2, NULL);\n pthread_cond_init(&cond, NULL);\n printf("Task Number:");\n scanf_s("%d", &n);\n for (int i = 0; i < thread_count; i++)\n pthread_create(&thread_handles[i], NULL, task, (void*)i);\n for (int i = 0; i < n; i++) {\n pthread_mutex_lock(&mutex2);\n EnQueue(&Q, i);\n Sleep(1);\n pthread_cond_signal(&cond);\n pthread_mutex_unlock(&mutex2);\n }\n finished = 1;\n pthread_cond_broadcast(&cond);\n for (int i = 0; i < thread_count; i++)\n pthread_join(thread_handles[i], NULL);\n pthread_mutex_destroy(&mutex);\n pthread_cond_destroy(&cond);\n free(thread_handles);\n return 0;\n}\nvoid* task(void* rank) {\n int my_rank = (long)rank;\n int my_task;\n QueueNode** p = &(Q.front->next);\n while (1) {\n pthread_mutex_lock(&mutex2);\n if (finished) {\n if (*p == NULL) {\n pthread_mutex_unlock(&mutex2);\n break;\n }\n DeQueue(&Q, &my_task, my_rank);\n pthread_mutex_unlock(&mutex2);\n printf("From thread %ld: Task no.%-3d result->%5d\n", my_rank, my_task, my_task * 10);\n\n }\n else {\n while(pthread_cond_wait(&cond, &mutex2)!=0);\n //pthread_mutex_lock(&mutex2);\n DeQueue(&Q, &my_task, my_rank);\n pthread_mutex_unlock(&mutex2);\n Sleep(2);\n printf("From thread %ld: Task no.%-3d result->%5d\n", my_rank, my_task, my_task * 10);\n }\n }\n


原文地址: https://www.cveoy.top/t/topic/pPl3 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录