メインスレッドが接続を取得してスレッドに渡し、スレッドがそれを処理するスレッドプールを使用してWebサーバーをプログラムしようとしています。
各スレッドの構造体と、それらを保持するためのworkQueueがあります
struct worker {
pthread_t* thread;
struct queue* workerQueue;
char* busy;
int connfd;
int id;
};
struct queue {
int start;
int end;
int size;
struct worker* workers;
};
メインスレッドはキューとスレッドを設定し、接続をループします
struct queue* workerQueue;
workerQueue = (struct queue*) constructQueue(10);
int j;
int* testParam;
//create workers and put in queue
for(j=0;j<5;j++)
{
struct worker* w = &(workerQueue->workers[j]);
w = (struct worker*)constructWorker(processConnection,testParam, workerQueue,j);
queueAdd(workerQueue,w);
}
connection = accept(fd, (struct sockaddr *) &cliaddr, &cliaddrlen);
puts("got connection\n");
w =(struct worker*) queueRemove(workerQueue);
//w->connfd = connection;
w->busy = "BUSY";
printf("Worker %d has accepted a connection and is %s\n",w->id,w->busy);
これらの2つの関数を使用します。
struct queue* constructQueue(int numThreads)
{
struct queue* q = (struct queue *)malloc(sizeof(struct queue));
q->start = 0;
q->end = 0;
q->workers = (struct worker* )malloc(sizeof(struct worker)*numThreads);
q->size = numThreads;
return q;
}
struct worker* constructWorker(void* (*function)(void*),void* param, struct queue* wq, int i)
{
struct worker* w = (struct worker*)malloc(sizeof(struct worker));
w->workerQueue = wq;
char * busy = (char*)malloc(10);
w->busy= "IDLE";
w->connfd = 0;
w->id = i;
pthread_t t;
w->thread = &t;
pthread_create(w->thread,NULL,function,w);
return w;
}
...そしてスレッドが使用する機能は
void* processConnection(void* serverThread)
{
//cast serverthread
struct worker* w;
char* b;
int threadID;
w = (struct worker*)serverThread;
b = w->busy;
threadID = w->id;
while (1)
{
char c[10];
printf("\nbusy: %s, thread: %d\n",b,threadID);
gets(c)
;
私がしたいのは、ビジーをIDLEに設定して、ワーカーを作成し、ビジーウェイトを開始することです。次に、メインループで、接続が受け入れられてワーカーに割り当てられ、ワーカーのビジー値がBUSYに設定されます。次に、processConnectionsで、スレッドがビジーの場合、実際に処理する必要があります。問題は、キューに値ではなくポインターが含まれているにもかかわらず、メインスレッドのワーカーを更新しても、processConnectionのワーカーの値に影響を与えていないように見えることです。ビジーをビジーに設定してメインループに出力させることはできますが、ビジーの値はprocessConnectionでは常にIDLEです。何か案は?