Producer-consumer problem multiprocessing solution in C with details
Problem
Producer-consumer problem is a classical problem in concurrency programming, I want to solve it by multiprocessing method. Multiprocessing method need more knowledges than multithreading method, because different process need to communicate with each other.
Process can communicate with each other by IPC (Inter-Process Communication), I chose a type of IPC , share memory, to implement.
Solutions
The key to solve the producer-consumer problem is synchronization, there is another point that seems easy to solve, that is comsumer comsume producer’s products. In multiprocessing case, comsumer process have to communicate with producer process to know where product is. So, 2 keys to solve the problem:
- Synchronization
- Communication
In C language, header file *<sys/sem.h>* helps us solve the first one, header file *<sys/shm.h>* help us solve the second one.
Implementation
I defined two types in my_type.h
:
product
: simulate produced products.shm_manage
: used to shared memory, indicate used memory range in shared memory.
1 | // my_type.h |
I wrapped 4 method of semaphore operation:
set_sem_value
: set semaphoresem_id
‘ssem_num
tovalue
del_sem_value
: delete semaphoresem_id
sem_p
: minus 1 from semaphoresem_id
‘ssem_num
sem_v
: add 1 to semaphoresem_id
‘ssem_num
1 | // my_sem_ops.h |
In producer:
- ftok() use a file to get a IPC id, I used file ‘.’, that means producers and consumers must run in same directory, or they will have differ IPC id.
semopts.buf->sem_otime == 0
to determine whether it’s first producer, first producer have to initiate three semaphores.- only
union semun semopts;
is not enough, will causesemctl()
‘s error: bad address. - Need
struct semid_ds mysemds;semopts.buf = &mysemds;
- only
1 | // producer.c |
1 | // consumer.c |