我正在尝试使用线程池对 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);
使用这两个功能..
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)
;
我想要发生的是:创建工人,忙设置为空闲,并开始忙于等待。然后在主循环中,一个连接被接受并分配给一个worker,worker的busy值被设置为BUSY。然后在 processConnections 中,如果一个线程很忙,它应该实际处理它。问题是,虽然我的队列包含指针而不是值,但当我在主线程中更新工作人员时,它似乎不会影响 processConnection 中工作人员的值。我可以将busy设置为BUSY并让它在主循环中打印出来,但是busy的值在processConnection中总是IDLE。有任何想法吗?