c++ - Synchronizing mutiple processes in C with shared memory -
i have program creates child processes in loop fork(). child create other processes well.
all processes must increment count, , count must displayed @ end.
to used simple locking system. shared memory of size 2. there 2 variable of type sig_tomic_t: count , lock.
when process wants increment count sets lock 1, increments count, sets lock 0. otherwise, if lock 1, process sleeps.
here code segment of interest.
for(i = 1; <= 10; i++) { if((pid = fork()) < 0) { perror("error fork!"); exit(2); } if(*lock == 0) { *lock = 1; *count = *count + 1; *lock = 0; } else { while(*lock == 1) { sleep(1); } } }
the problem though used simple locking system, count isn't incremented correctly.
Comments
Post a Comment