First up I forgot to add pthread_detach() to that last bit of code -- I edited it in now, but if daghenningsorbo comes back, note that.
Originally Posted by
Codeplug
>> If you then just use a global flag:
That's not proper synchronization. That's what pthread_mutex is for.
No doubt that is what pthread_mutex is for, but if by "synchronization" and "proper" you mean "how I do it" or "my preferred method" fine, but there is nothing wrong, improper, undefined, dangerous, etc. about just using a global:
Code:
#include <stdio.h>
#include <pthread.h>
int Lock = 0, Total = 0;
void *myfunc(void *count) {
int *tmp = count, id = *tmp;
printf("Lock: %d ID: %d\n",Lock,id); fflush(stdout);
if (!Lock) {
Lock = id;
if (Lock != id) { /* double check lock to prevent simultaneous access */
(sleep(1));
myfunc(&id);
} else {
sleep(1); /* simulate our time consuming process */
Total++;
Lock = 0;
}
}
else { /* the basic poll loop */
(sleep(1));
myfunc(&id);
}
pthread_exit(NULL);
}
int main() {
int i;
pthread_t mythread[10];
for (i=0; i<10; i++) {
printf(" in main() i=%d ",i); fflush(stdout);
pthread_create(&mythread[i],NULL,myfunc,(void*)&i);
pthread_detach(mythread[i]);
}
while (Total<10) {
printf("->%d<-",Total);
sleep(1);
}
printf("Total: %d -- complete.\n",Total);
return 0;
}
Compile: gcc test.c -lpthread
IMO what the OP is suggesting is simple and straightforward and this method will work flawlessly. It also has the advantage of being "familiar" and not leaning too heavily on the library -- just in case you do not have an extra afternoon to spend pouring over the rather tedious pthread docs.