嗨,我想實現一個客戶端服務器程序,通過共享內存相互通信。在服務器端我有兩個線程。一個作家線程和一個讀者線程。寫線程把一些數據到隊列中,讀者線程讀取,並將數據傳遞到客戶端...在線程中使用共享內存
這裏是我的讀者不知所云,問題是,我的兩個線程創建成功,但它不會進入我在線程例程中指定的while循環中...現在我的問題是:在線程調用 線程時,是否可以在線程例程中使用共享內存?
void *reader_thread(void * id)
{
.....
shm_addr = shmat(shm_id,NULL,0);
if(shm_addr==(void *)-1)
{
perror("shmat error");
exit(1);
}
while (1)
{
printf("Here in thread reader!");
sem_wait(&queue_t->full);
sem_wait(&queue_t->mutex);
if (queue_t->tail != queue_t->head)
{
memmove(imgPath,queue_t->imgAddr[queue_t->head],strlen(queue_t->imgAddr[queue_t->head])-1);
imgPath[strlen(queue_t->imgAddr[queue_t->head])-1] = '\0';
queue_t->head = (queue_t->head + 1) % QUEUE_SIZE;
}
sem_post(&queue_t->mutex);
sem_post(&queue_t->empty);
...
sem_wait(&shared->shm_sem);
memset(shm_addr,0,SHMSZ);
memcpy(shm_addr, &imgPath, sizeof(imgPath));
sem_post(&shared->shm_sem);
}
return 0;
}
///////////////////////////////
int main(int argc , char *argv[])
{
pthread_t writer_t, reader_t;
queue_t = (struct Queue*) malloc(sizeof(Queue));
queue_t->head = 0;
queue_t->tail = 0;
sem_init(&queue_t->empty, 0, QUEUE_SIZE);
sem_init(&queue_t->full, 1, 0);
sem_init(&queue_t->mutex, 1, 1);
shared = (struct shared_mem*) malloc(sizeof(shared_mem));
sem_init(&shared->shm_sem, 1, 1);
int shmid;
key_t key;
char *shm_addr;
key=1234;
//Create the segment and set permissions.
if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0)
{
perror("shmget error");
if(errno==EEXIST)
{
fprintf(stderr,"shared memory exist... ");
exit(1);
}
}
fprintf(stdout,"shared mem created with id: %d\n",shmid);
//Now we attach the segment to our data space.
if ((shm_addr = shmat(shmid, NULL, 0)) == (char *) -1)
{
perror("shmat error");
exit(1);
}
// Zero out memory segment
memset(shm_addr,0,SHMSZ);
if(pthread_create(&reader_t , NULL , reader_thread , &shmid) < 0)
{
perror("could not create reader thread");
return 1;
}
pthread_detach(reader_t);
puts("reader thread assigned");
if(pthread_create(&writer_t , NULL , writer_thread , NULL) < 0)
{
perror("could not create writer thread");
return 1;
}
pthread_detach(writer_t);
puts("writer thread assigned");
//if(shmdt(shm_addr) != 0)
// fprintf(stderr, "Could not close memory segment.\n");
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
it's可能。你創造了SHM嗎?我只看到shmat,服務器應該首先創建它,也是信號量 – mch
是的,我已經在主函數中創建了它,並將shmid傳遞給讀者線程 – user2236835
我是否認爲在main()的末尾已經分離了pthread並破壞了共享內存區域......而pthreads可能已經開始,也可能沒有開始,可能會或可能沒有完成? –