
WorkerThreadを用いたプログラムを作成しております。
概要
- リストコマンドラインに入力された数字によって動作を変更し、
サブスレッドで入力され次第随時実行していきます。
- キューには連結リストを使用しています。
環境
VMware 7.1.4 build-3848939
Unbuntu Linux
C言語
1#define _CRT_SECURE_NO_WARNINGS 2 3#include "stdlib.h" 4#include "stdio.h" 5#include "pthread.h" 6#include "CheckFile.h" 7#include "Integration.h" 8#include "Analysis.h" 9#include "AddList.h" 10#include "freeListPointer.h" 11#include "define.h" 12 13typedef struct Queue 14{ 15 int action; 16 struct Queue *next; 17 struct Queue *prev; 18}Queue; 19 20pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 21pthread_cond_t MainCond; 22pthread_mutex_t EventMutex; 23 24 25 26void *SubThread(void *p_arg); 27 28//Global Variable for End SubThread. 29int SubThreadEnd = 0; 30 31//Global Variable for count queue number. 32int count = 0; 33 34//Global Pointer Valiable for keep head pointer of queue. 35Queue *head = NULL; 36 37//Global Variable for end programs. 38int EndCount = 0; 39 40Queue *Enqueue(int action, Queue *p) 41{ 42 43 pthread_mutex_lock(&EventMutex); 44 Queue *ptr = (Queue *)malloc(sizeof(Queue)); 45 46 if(NULL == ptr) 47 { 48 printf("Could not get memory area.\n"); 49 } 50 51 if(p == NULL) 52 { 53 head = ptr; 54 ptr->action = action; 55 ptr->prev = NULL; 56 ptr->next = NULL; 57 pthread_mutex_unlock(&EventMutex); 58 return ptr; 59 } 60 61 ptr->action = action; 62 p->next = ptr; 63 ptr->prev = p; 64 ptr->next = NULL; 65 66 count++; 67 68 pthread_mutex_unlock(&EventMutex); 69 return ptr; 70 71} 72void Action(int action) 73{ 74 if(action == 1) 75 { 76 } 77 if(action == 2) 78 { 79 } 80 if(action == 3) 81 { 82 } 83//処理は省きます。 84 85void *SubThread(void *p_arg) 86{ 87 int loop = 0; 88 89 90 printf("SubThread - Starting.\n"); 91 92 while(1) 93 { 94 while(NULL != head) 95 { 96 pthread_mutex_lock(&EventMutex); 97 98 //Dequeue by excuting the function. 99 Action(head->action); 100 head = head->next; 101 102 pthread_mutex_unlock(&EventMutex); 103 pthread_cond_signal(&MainCond); 104 } 105 106 } 107} 108 109void main() 110{ 111 pthread_t th; 112 int action = 0; 113 Queue *p = NULL; 114 115 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; 116 117 pthread_create(&th,NULL,SubThread,NULL); 118 119 pthread_cond_init(&MainCond, NULL); 120 pthread_mutex_init(&mutex, NULL); 121 122 while(1) 123 { 124 125 printf("Select the action.\n"); 126 printf("(1).Loading file.\n"); 127 printf("(2).Select analysis method.\n"); 128 printf("(3).Exit programs.\n"); 129 130 scanf("%d",&action); 131 132 p = Enqueue(action,p); 133 134 pthread_cond_wait(&MainCond,&mutex); 135 136 if(EndCount != 0) 137 { 138 break; 139 } 140 141 } 142 printf("Exit program.\n"); 143}
実行後、1回目の入力では、正常にサブスレッドが機能していることが確認されたのですが、
2回目以降、main関数でコマンドラインより入力を行うとEnqueueを実行し終わったところで
プログラムがとまってしまいます。(エラーなどによる動作停止ではなく、メインでwaitして
いるのにサブスレッドが動きません。)
なぜサブスレッドは無限ループにしているにもかかわらずとまってしまっているのでしょうか。

バッドをするには、ログインかつ
こちらの条件を満たす必要があります。