c語言 進程 共享內存 pthread_mutex 互斥鎖 數字累加

#include<sys/ipc.h>  
#include<stdio.h>  
#include<stdlib.h>  
#include<unistd.h>  
#include<signal.h>  
#include<sys/types.h>  
#include<sys/stat.h>  
#include<string.h>  
#include<errno.h>  
#include<sys/shm.h> 
#include<sys/wait.h> 
#include <semaphore.h>
#include <pthread.h>


struct Shm {
    int now;
    int sum;
    pthread_mutex_t mutex;
};

struct Shm *shm = NULL;

void do_add(int max, int x) {
    while (1) {
        pthread_mutex_lock(&shm->mutex);
        if (shm->now > max) {
            pthread_mutex_unlock(&shm->mutex);
            break;
        }
        printf("<%d> : %d %d\n", x, shm->now, shm->sum);
        shm->sum += shm->now;
        shm->now += 1;
        pthread_mutex_unlock(&shm->mutex);
    }
}

int main(int argc, char **argv) {
    if (argc != 3) {
        fprintf(stderr, "Usage : %s max ins\n", argv[0]);
        exit(1);
    }
    
    int max = atoi(argv[1]);
    int ins = atoi(argv[2]);
    pid_t pid;
    int shmid;
    key_t key = ftok(".", 199);
    
    if ((shmid = shmget(key, sizeof(struct Shm), IPC_CREAT | 0666)) < 0) {
        perror("shmget");
        return 1;
    }
    
    if ((shm = (struct Shm *)shmat(shmid, NULL, 0)) < 0) {
        perror("");
        return 1;
    }

    memset(shm, 0, sizeof(shm));

    pthread_mutexattr_t attr;
    pthread_mutexattr_init(&attr);
    pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);

    pthread_mutex_init(&shm->mutex, &attr);

	int x;
	for (int i = 0; i < ins; i++) {
        if ((pid = fork()) < 0) {
            perror("fork");
            return 1;
        }

        if (pid == 0) {
            x = i;
            break;
        }
    }

    if (pid == 0) {
        do_add(max, x);
        printf("%d exit\n", x);
        exit(0);
    }
    while (ins) {
        wait(NULL);
        ins--;
    }

    printf("sum: %d !\n", shm->sum);

    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章