从c中的共享内存读取和写入int

时间:2020-03-30 13:59:55

标签: c pthreads shared-memory

我正在尝试创建一个程序,其中一个线程将一个整数写入共享内存位置,然后另一个线程读取并打印该整数。我面临的问题是第二个线程继续将整数读取为-1。 这是我的代码:

#include <stdio.h> 
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h> 
#include <unistd.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>


struct args {
    void* memptr;
    sem_t* semptr;
};

void *p1(void *vargp) 
{
    void* memory = ((struct args*)vargp)->memptr;
    sem_t* semaphore = ((struct args*)vargp)->semptr;
    //sem_wait(semaphore);
    //sleep(0.5);
    for(int i=0; i<=10; i++)
    {
        if (!sem_wait(semaphore)) {
            printf("got in if p1\n");
            sprintf(memory, "%d", i);
            sem_post(semaphore);
            sleep(1);
        }
    }
    if (!sem_wait(semaphore)) {
        sprintf(memory, "%d", 0);
        sem_post(semaphore);
        sleep(1);
    }
    sleep(0.1);
}

void *p2(void *vargp) 
{
    void* memory = ((struct args*)vargp)->memptr;
    sem_t* semaphore = ((struct args*)vargp)->semptr;
    sleep(0.1);
    while(1)
    {
        if (!sem_wait(semaphore)) {
            printf("got in if p2\n");
            if((int)memory == 0){
                break;
            }
            printf("%d\n", (int)memory);
            sem_post(semaphore);
            sleep(1);
        }
    }
} 

const int ByteSize = 4;
const char* SharedName = "memNameTest";
const char* SemaphoreName = "semNameTest";


int main() 
{   
    int fd = shm_open(SharedName, O_RDWR, 0644);
    ftruncate(fd, ByteSize);
    void* memptr = mmap(0, ByteSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    sem_t* semptr = sem_open(SemaphoreName, O_CREAT, 0644, 0);
    sem_post(semptr);
    struct args *Share = (struct args *)malloc(sizeof(struct args));
    Share->memptr = memptr;
    Share->semptr = semptr;

    pthread_t thread1, thread2; 
    printf("Before Thread\n"); 
    pthread_create(&thread1, NULL, p1, (void*)Share);
    pthread_create(&thread2, NULL, p2, (void*)Share);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    printf("After Thread\n");



    munmap(memptr, ByteSize);
    close(fd);
    sem_close(semptr);
    unlink(SharedName);
    return 0;
    exit(0); 
}

我尝试将(int)memory更改为*((int*)memory),但这导致了细分错误。

(编辑) 如建议的那样,我在单线程程序中尝试了此操作,并使它按如下方式工作:

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h> 
#include <unistd.h>
#include <string.h>

int main()
{

    /* the size (in bytes) of shared memory object */
    const int SIZE = 4;
    /* name of the shared memory object */
    const char* SharedName = "memoryInt";
    /* create the shared memory object */
    int shm_fd = shm_open(SharedName, O_CREAT | O_RDWR, 0644);
    /* configure the size of the shared memory object */
    ftruncate(shm_fd, SIZE);
    /* memory map the shared memory object */
    void* memptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0); 

    for(int i=1; i<=10; i++){
        /* write to the shared memory object */
        //sprintf(memptr, "%d", i);
        memcpy(memptr, &i, sizeof(int));
        printf("%d\n", *((int*)memptr));
        sleep(1);
    }

    return 0;
}

尽管这在多线程程序中仍然不起作用,因为我遇到了分段错误。 这是输出:

Before Thread
got in if p1
Segmentation fault

1 个答案:

答案 0 :(得分:0)

首先,您必须在编译程序时显示终端上发生的情况。 其次,函数sprintf具有声明:

batch.setData(
   db.document('Path/to/firestore/document'),
   {"key": value},
   SetOptions(merge: true)
);

这意味着p1将写入以null结尾的字符串。在您的代码中,我不明白为什么您使用空指针import pandas as pd import os import tensorflow as tf from time import time from tensorflow.python.keras.layers.core import Dense from tensorflow.python.keras.models import Sequential from tensorflow.python.keras.layers import LSTM from tensorflow.python.keras.callbacks import TensorBoard import matplotlib.pyplot as plt from sklearn.preprocessing import MinMaxScaler import numpy as np model = Sequential() model.add(LSTM(units=20, return_sequences=True, input_shape=(1, 7), activation='softsign')) model.add(LSTM(units=50, return_sequences=True, activation='softsign')) model.add(LSTM(units=50, return_sequences=True, activation='softsign')) model.add(LSTM(units=50, return_sequences=True, activation='softsign')) model.add(LSTM(units=20, activation='softsign')) model.add(Dense(units=1, activation='sigmoid')) model.compile(loss='mse', optimizer='Nadam',metrics=['mse']) tensorboard = TensorBoard(log_dir="logs/fit") result = model.fit(X_train, Y_train, batch_size=200, epochs=5, validation_split=0.1, verbose=1, callbacks=[tensorboard]) %load_ext tensorboard %tensorboard --logdir logs 而不是使用char指针作为描述。在应用到多线程之前,应该使用单线程来验证读/写功能。