concurrency - C Semaphore strange precedence behavior -
i'm practicing concurrency in c, , seem encounter problems semaphores. i'm using xcode 6.3.2 in macosx.
here sample program seems act strangely: purpose of example print either abcd or bacd strings
#include <stdio.h> #include <semaphore.h> #include <pthread.h> #include <errno.h> void *thread1(void*); void *thread2(void*); sem_t *sem0, *sem1, *sem2;; int main(int argc, const char * argv[]) { pthread_t t1, t2; sem0 = sem_open("sem0", o_creat, 0600, 2); sem1 = sem_open("sem1", o_creat, 0600, 0); sem2 = sem_open("sem2", o_creat, 0600, 0); // quick check if (sem0 == sem_failed || sem1 == sem_failed || sem2 == sem_failed) { printf("something went wrong\n"); return 0; } pthread_create(&t1, null, thread1, null); pthread_create(&t2, null, thread2, null); pthread_join(t1, null); pthread_join(t2, null); sem_close(sem0); sem_close(sem1); sem_close(sem2); return 0; } void *thread1(void* arg) { int n=0; while (n<10) { sem_wait(sem0); printf("a"); fflush(stdout); sem_wait(sem1); printf("c"); fflush(stdout); sem_post(sem2); n++; } pthread_exit(null); } void *thread2(void* arg) { int n=0; while (n<10) { sem_wait(sem0); printf("b"); fflush(stdout); sem_post(sem1); sem_wait(sem2); printf("d\n"); fflush(stdout); sem_post(sem0); sem_post(sem0); n++; } pthread_exit(null); }
if implemented correctly semaphores, result either abcd or bacd, in reality whole variety of strange output.
i include part of output here
abcd bad cabcd bad cbad cbad cbad cbad cbad cbad c
is able me? in advance
important edit: downloaded ubuntu, , code working smoothly there, no problems @ all. so, resume
- macosx 10.10.3 xcode 6.3.2 --> not working
- ubuntu 15.04 --> working properly
don't know why.
your problem printf
output buffered , shared between threads. you'd have ensure empty buffer fflush
before posting on semaphores.
Comments
Post a Comment