Sunday, 15 February 2015

c - pthreads and concurrency -



c - pthreads and concurrency -

i have next code:

#include <pthread.h> #include <stdio.h> #include <stdlib.h> #define loops 10000 void *run(void *arg) { int id = strtol(arg,null,0); int i; for(i=0; i<loops; i++) { printf("in %d.\n",id); } } int main() { pthread_t p1,p2; void *res; pthread_create(&p1,null,run,"1"); pthread_create(&p2,null,run,"2"); pthread_join(p1,&res); pthread_join(p2,&res); homecoming 0; }

when run this, either string "in 1" displays 10000 times consecutively "in 2" displays 10000 times consecutively or vice versa. shouldn't strings alternating , not displaying consecutively here?

the order in threads interleaved scheduler not deterministic (...well scheduler's/kernel's point of view). should not create assumptions order.

in this situation experience either 1 of threads allowed finish whole work before scheduler ->preempts , allows other thread run.

c multithreading concurrency pthreads

No comments:

Post a Comment