If I make 2 detached threads which count to 10 and write the message on STDOUT, everything is OK. But, if I put sleep() into the loop of the thread function (line (1)), then only the first thread is executed and the loop within the thread for just one time. Why?
Also, everything works fine if I use joinable thread with pthread_join(), then there's no problem with sleep(). So, why detached thread makes the problem?Code:#include <stdio.h> #include <pthread.h> /* Thread start function, counts to 10 and exits. */ void* f(void* arg) { char* param = (char*)arg; int i; for (i = 1; i <= 10; i++) { printf("\n%s %d", param, i); sleep(1);/* (1) */ } return NULL; } int main(void) { pthread_attr_t attr1; pthread_attr_t attr2; pthread_t th1; pthread_t th2; char arg1[10] = "thread1"; char arg2[10] = "thread2"; pthread_attr_init(&attr1); pthread_attr_init(&attr2); pthread_attr_setdetachstate(&attr1, PTHREAD_CREATE_DETACHED); pthread_attr_setdetachstate(&attr2, PTHREAD_CREATE_DETACHED); pthread_create(&th1, &attr1, &f, arg1); pthread_create(&th2, &attr2, &f, arg2); printf("\n"); return 0; }
Thanks in advance.



LinkBack URL
About LinkBacks


