Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/mman.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <semaphore.h>
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <time.h>
- #include <pthread.h>
- #include <errno.h>
- typedef struct Arguments {
- bool* flag;
- timespec* tm;
- sem_t* semForWrite;
- sem_t* semForRead;
- unsigned int* localVar;
- } arguments;
- void *thread(void *args){
- puts("read thread started");
- arguments *argument = (arguments*) args;
- (*(argument->tm)).tv_sec = 0;
- (*(argument->tm)).tv_nsec = 100000000;
- while (*(argument->flag)){
- while (sem_trywait(argument->semForWrite) != 0) {
- nanosleep(argument->tm, NULL);
- if (!*(argument->flag))
- return 0;
- }
- printf("Readed: %u\n", *(argument->localVar));
- sem_post(argument->semForRead);
- sleep(1);
- }
- pthread_exit(NULL);
- }
- int main(){
- arguments args;
- sem_t *semForWrite;
- sem_t *semForRead;
- unsigned int *localVar;
- char SemForReadName[] = "some_random_name_read_7";
- char SemForWriteName[] = "some_random_name_write_7";
- char SharedMemoryName[] = "some_random_mem_name_7";
- bool flag = true;
- pthread_t threadInit;
- timespec tm;
- int fd = shm_open(SharedMemoryName, O_CREAT | O_RDWR, 0777);
- ftruncate(fd, sizeof(unsigned int));
- localVar = (unsigned int*)mmap(0, sizeof(unsigned int), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
- semForWrite = sem_open(SemForWriteName, O_CREAT, 0644, 0);
- semForRead = sem_open(SemForReadName, O_CREAT, 0644, 0);
- args.tm = &tm;
- args.flag = &flag;
- args.localVar = localVar;
- args.semForRead = semForRead;
- args.semForWrite = semForWrite;
- if(pthread_create(&threadInit, NULL, &thread, (void*)&args)){
- return EXIT_FAILURE;
- }
- getchar();
- flag = false;
- pthread_join(threadInit, NULL);
- sem_close(semForRead);
- sem_unlink(SemForReadName);
- sem_close(semForWrite);
- sem_unlink(SemForWriteName);
- munmap(&localVar, 4);
- close(fd);
- shm_unlink(SharedMemoryName);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement