gpt4 book ai didi

c - 在线程中使用共享内存

转载 作者:行者123 更新时间:2023-11-30 17:31:14 27 4
gpt4 key购买 nike

嗨,我想实现一个通过共享内存相互通信的客户端-服务器程序。在服务器端我有两个线程。一个编写者线程和一个读者线程。写入器线程将一些数据放入队列中,读取器线程从中读取数据并将数据传递到客户端...

这是我的读者线程...问题是我的两个线程已成功创建,但它没有进入我在线程例程中指定的 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;
}

最佳答案

之前的问题已经解决了...我用 pthread_join 替换了 pthread_detach 并把 of 放在 main 的末尾。但现在我在客户端遇到了段错误:client get segmentation fault when attach to shared memory

关于c - 在线程中使用共享内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24746141/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com