我想編程一個Web服務器,使用線程池,其中主線程需要一個連接,將它傳遞給線程,並且線程處理它。不能共享pthread之間的變量,值是不同的
我必須爲每個線程結構和工作隊列追究他們
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)
;
我想要發生的事情是:工人被創建,忙於設置爲空閒,並開始忙於等待。那麼在主循環中,接受連接並將其分配給工人,並且工人繁忙值被設置爲繁忙。那麼在processConnections中,如果線程繁忙,它應該實際處理它。問題是,雖然我的隊列包含的指針不是值,但當我更新主線程中的工作人員時,似乎並沒有影響processConnection中工作人員的值。我可以將busy設置爲BUSY,並將它打印在主循環中,但busy的值始終在processConnection中爲IDLE。有任何想法嗎?
如果同時訪問一個變量,訪問它應該使用互斥量進行序列化。對於* pthreads *,可以使用'pthread_mutex_t'類型的變量來完成。請閱讀man pthread_mutex_init。 – alk 2013-02-26 07:20:19