Конспекты

threads.c

Код · 52 строки · 2 КБ

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 256

static int shmid;
static pthread_t writer_tid;

// Поток-писатель: создаёт сегмент и кладёт в него строку
static void *writer_thread(void *arg) {
    (void)arg;
    shmid = shmget(IPC_PRIVATE, SHM_SIZE, IPC_CREAT | 0600);
    if (shmid == -1) {
        perror("shmget");
        return NULL;
    }
    char *mem = shmat(shmid, NULL, 0);
    if (mem == (void *)-1) {
        perror("shmat");
        return NULL;
    }
    strcpy(mem, "Сообщение из потока-писателя через разделяемую память");
    printf("Поток-писатель: записал строку в сегмент %d\n", shmid);
    shmdt(mem);
    return NULL;
}

// Поток-читатель: ждёт писателя, читает строку и удаляет сегмент
static void *reader_thread(void *arg) {
    (void)arg;
    pthread_join(writer_tid, NULL);
    char *mem = shmat(shmid, NULL, SHM_RDONLY);
    if (mem == (void *)-1) {
        perror("shmat");
        return NULL;
    }
    printf("Поток-читатель: прочитал \"%s\"\n", mem);
    shmdt(mem);
    shmctl(shmid, IPC_RMID, NULL);
    return NULL;
}

int main() {
    pthread_t reader_tid;
    pthread_create(&writer_tid, NULL, writer_thread, NULL);
    pthread_create(&reader_tid, NULL, reader_thread, NULL);
    pthread_join(reader_tid, NULL);
    return 0;
}